1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
|
import { mkdir, readFile, writeFile } from "fs/promises";
import { join } from "path";
import { tmpdir } from "os";
import { eq, sql } from "drizzle-orm";
import { db } from "../db";
import { codeEmbeddings } from "../db/schema";
import { getBlob } from "../git/repository";
import { hashEmbed, tokenize, isCodeFile } from "./semantic-search";
export const EMBEDDING_DIM = 1024;
const SNIPPET_BYTES = 500;
const VOYAGE_BATCH = 128;
const MAX_EMBED_BYTES = 32 * 1024;
const VOYAGE_MODEL = "voyage-code-3";
const FALLBACK_MODEL = "gluecron-tfidf-1024";
let _cacheDirPromise: Promise<string> | null = null;
async function getCacheDir(): Promise<string> {
if (_cacheDirPromise) return _cacheDirPromise;
_cacheDirPromise = (async () => {
const dir =
process.env.GLUECRON_SEMANTIC_CACHE_DIR ||
join(tmpdir(), "gluecron-semantic-cache");
try {
await mkdir(dir, { recursive: true });
} catch {
}
return dir;
})();
return _cacheDirPromise;
}
async function cacheKey(model: string, blobSha: string): Promise<string> {
const data = new TextEncoder().encode(`${model}:${blobSha}`);
const hash = await crypto.subtle.digest("SHA-256", data);
return Array.from(new Uint8Array(hash))
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
}
async function readCached(
model: string,
blobSha: string
): Promise<number[] | null> {
try {
const dir = await getCacheDir();
const key = await cacheKey(model, blobSha);
const path = join(dir, `${key}.json`);
const text = await readFile(path, "utf8");
const v = JSON.parse(text);
if (Array.isArray(v) && v.length === EMBEDDING_DIM) return v as number[];
return null;
} catch {
return null;
}
}
async function writeCached(
model: string,
blobSha: string,
vec: number[]
): Promise<void> {
try {
const dir = await getCacheDir();
const key = await cacheKey(model, blobSha);
const path = join(dir, `${key}.json`);
await writeFile(path, JSON.stringify(vec), "utf8");
} catch {
}
}
function voyageKey(): string | null {
return process.env.VOYAGE_API_KEY || null;
}
export function semanticIndexProvider(): "voyage" | "fallback" {
return voyageKey() ? "voyage" : "fallback";
}
function fallbackEmbed(text: string): number[] {
return hashEmbed(tokenize(text), EMBEDDING_DIM);
}
interface EmbedResult {
vectors: number[][];
model: string;
}
async function voyageEmbed(
apiKey: string,
texts: string[],
inputType: "document" | "query"
): Promise<EmbedResult | null> {
const all: number[][] = [];
for (let i = 0; i < texts.length; i += VOYAGE_BATCH) {
const slice = texts.slice(i, i + VOYAGE_BATCH);
try {
const resp = await fetch("https://api.voyageai.com/v1/embeddings", {
method: "POST",
headers: {
"content-type": "application/json",
authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify({
input: slice,
model: VOYAGE_MODEL,
input_type: inputType,
}),
});
if (!resp.ok) return null;
const json: any = await resp.json();
const data = Array.isArray(json?.data) ? json.data : null;
if (!data || data.length !== slice.length) return null;
for (const row of data) {
const emb = row?.embedding;
if (!Array.isArray(emb) || emb.length !== EMBEDDING_DIM) return null;
all.push(emb as number[]);
}
} catch {
return null;
}
}
return { vectors: all, model: VOYAGE_MODEL };
}
export async function embedOne(
text: string,
inputType: "document" | "query"
): Promise<{ vector: number[]; model: string }> {
if (_embedderOverride) {
return _embedderOverride(text, inputType);
}
const key = voyageKey();
if (key) {
const out = await voyageEmbed(key, [text], inputType);
if (out && out.vectors[0]) {
return { vector: out.vectors[0], model: out.model };
}
}
return { vector: fallbackEmbed(text), model: FALLBACK_MODEL };
}
type Embedder = (
text: string,
inputType: "document" | "query"
) => Promise<{ vector: number[]; model: string }>;
let _embedderOverride: Embedder | null = null;
export function __setEmbedderForTests(fn: Embedder | null): void {
_embedderOverride = fn;
}
const MAX_FILES_PER_PUSH = 50;
export async function indexChangedFiles(args: {
repositoryId: string;
ownerName: string;
repoName: string;
commitSha: string;
changedPaths: string[];
}): Promise<{ indexed: number; skipped: number; model: string }> {
const { repositoryId, ownerName, repoName, commitSha, changedPaths } = args;
if (!repositoryId || !commitSha || !changedPaths.length) {
return { indexed: 0, skipped: 0, model: FALLBACK_MODEL };
}
const seen = new Set<string>();
const candidates: string[] = [];
for (const p of changedPaths) {
if (!p || seen.has(p)) continue;
seen.add(p);
if (!isCodeFile(p)) continue;
candidates.push(p);
if (candidates.length >= MAX_FILES_PER_PUSH) break;
}
if (!candidates.length) {
return { indexed: 0, skipped: changedPaths.length, model: FALLBACK_MODEL };
}
let indexed = 0;
let model = FALLBACK_MODEL;
for (const filePath of candidates) {
let blob: Awaited<ReturnType<typeof getBlob>> = null;
try {
blob = await getBlob(ownerName, repoName, commitSha, filePath);
} catch (err) {
blob = null;
}
if (!blob || blob.isBinary || !blob.content) continue;
const blobSha = await deriveBlobSha(blob.content);
const snippet = blob.content.slice(0, SNIPPET_BYTES);
const textToEmbed = `${filePath}\n${blob.content.slice(0, MAX_EMBED_BYTES)}`;
let vec: number[] | null = null;
let resolvedModel = FALLBACK_MODEL;
if (voyageKey()) {
const hit = await readCached(VOYAGE_MODEL, blobSha);
if (hit) {
vec = hit;
resolvedModel = VOYAGE_MODEL;
}
}
if (!vec) {
const hit = await readCached(FALLBACK_MODEL, blobSha);
if (hit) {
vec = hit;
resolvedModel = FALLBACK_MODEL;
}
}
if (!vec) {
try {
const out = await embedOne(textToEmbed, "document");
vec = out.vector;
resolvedModel = out.model;
if (vec && vec.length === EMBEDDING_DIM) {
void writeCached(resolvedModel, blobSha, vec);
}
} catch {
vec = null;
}
}
if (!vec || vec.length !== EMBEDDING_DIM) continue;
model = resolvedModel;
try {
await db
.insert(codeEmbeddings)
.values({
repositoryId,
filePath,
blobSha,
commitSha,
contentSnippet: snippet,
embedding: vec,
embeddingModel: resolvedModel,
updatedAt: new Date(),
})
.onConflictDoUpdate({
target: [codeEmbeddings.repositoryId, codeEmbeddings.filePath],
set: {
blobSha,
commitSha,
contentSnippet: snippet,
embedding: vec,
embeddingModel: resolvedModel,
updatedAt: new Date(),
},
});
indexed++;
} catch (err) {
if (process.env.DEBUG_SEMANTIC_INDEX === "1") {
console.warn(
`[semantic-index] upsert failed for ${ownerName}/${repoName}:${filePath}:`,
err instanceof Error ? err.message : err
);
}
}
}
return {
indexed,
skipped: candidates.length - indexed,
model,
};
}
async function deriveBlobSha(content: string): Promise<string> {
const data = new TextEncoder().encode(content);
const hash = await crypto.subtle.digest("SHA-256", data);
return Array.from(new Uint8Array(hash))
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
}
export interface SemanticHit {
filePath: string;
snippet: string;
score: number;
blobSha: string;
}
export async function searchSemantic(args: {
repositoryId: string;
query: string;
limit?: number;
}): Promise<SemanticHit[]> {
const { repositoryId, query } = args;
const limit = Math.max(1, Math.min(args.limit ?? 20, 100));
const q = (query || "").trim();
if (!q || !repositoryId) return [];
let queryVec: number[];
try {
const out = await embedOne(q, "query");
queryVec = out.vector;
} catch {
return [];
}
if (!queryVec || queryVec.length !== EMBEDDING_DIM) return [];
const vecLit = "[" + queryVec.join(",") + "]";
try {
const rows = await db
.select({
filePath: codeEmbeddings.filePath,
snippet: codeEmbeddings.contentSnippet,
blobSha: codeEmbeddings.blobSha,
score: sql<number>`1 - (${codeEmbeddings.embedding} <=> ${vecLit}::vector)`,
})
.from(codeEmbeddings)
.where(eq(codeEmbeddings.repositoryId, repositoryId))
.orderBy(sql`${codeEmbeddings.embedding} <=> ${vecLit}::vector`)
.limit(limit);
return rows.map((r) => ({
filePath: r.filePath,
snippet: r.snippet || "",
score: typeof r.score === "number" ? r.score : Number(r.score) || 0,
blobSha: r.blobSha,
}));
} catch {
return [];
}
}
export const __test = {
fallbackEmbed,
deriveBlobSha,
cacheKey,
MAX_FILES_PER_PUSH,
FALLBACK_MODEL,
VOYAGE_MODEL,
};
|