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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
|
import {
describe,
it,
expect,
beforeAll,
afterAll,
beforeEach,
} from "bun:test";
import { join } from "path";
import { rm, mkdir } from "fs/promises";
import { randomBytes } from "crypto";
import app from "../app";
import { clearRateLimitStore } from "../middleware/rate-limit";
import { initBareRepo, getRepoPath } from "../git/repository";
import {
indexChangedFiles,
searchSemantic,
embedOne,
__setEmbedderForTests,
__test,
EMBEDDING_DIM,
} from "../lib/semantic-index";
const HAS_DB = Boolean(process.env.DATABASE_URL);
const TEST_REPOS = join(
import.meta.dir,
"../../.test-repos-semantic-index-" + Date.now()
);
let HAS_PGVECTOR = false;
beforeAll(async () => {
process.env.GIT_REPOS_PATH = TEST_REPOS;
process.env.GLUECRON_SEMANTIC_CACHE_DIR = join(TEST_REPOS, "_cache");
clearRateLimitStore();
await rm(TEST_REPOS, { recursive: true, force: true });
await mkdir(TEST_REPOS, { recursive: true });
if (HAS_DB) {
HAS_PGVECTOR = await probePgvector();
}
});
afterAll(async () => {
__setEmbedderForTests(null);
await rm(TEST_REPOS, { recursive: true, force: true });
});
beforeEach(() => {
__setEmbedderForTests(null);
});
async function run(cmd: string[], cwd: string) {
const proc = Bun.spawn(cmd, { cwd, stdout: "pipe", stderr: "pipe" });
await new Response(proc.stdout).text();
await proc.exited;
}
async function seedRepo(owner: string, name: string, files: Record<string, string>) {
await initBareRepo(owner, name);
const bare = getRepoPath(owner, name);
const work = join(TEST_REPOS, "_work_" + randomBytes(4).toString("hex"));
await mkdir(work, { recursive: true });
await run(["git", "clone", bare, work], TEST_REPOS);
await run(["git", "config", "user.email", "t@gluecron.com"], work);
await run(["git", "config", "user.name", "T"], work);
await run(["git", "checkout", "-B", "main"], work);
for (const [path, content] of Object.entries(files)) {
const full = join(work, path);
await mkdir(join(full, ".."), { recursive: true });
await Bun.write(full, content);
}
await run(["git", "add", "-A"], work);
await run(["git", "commit", "-m", "seed"], work);
await run(["git", "push", "-u", "origin", "main"], work);
const { stdout } = await Bun.spawn(["git", "rev-parse", "main"], {
cwd: work,
stdout: "pipe",
});
const sha = (await new Response(stdout).text()).trim();
await rm(work, { recursive: true, force: true });
return sha;
}
function makeStubEmbedder(): (
text: string,
inputType: "document" | "query"
) => Promise<{ vector: number[]; model: string }> {
return async (text: string) => {
const v = new Array<number>(EMBEDDING_DIM).fill(0);
const lower = text.toLowerCase();
const KEYS = [
"fetch",
"database",
"config",
"user",
"render",
"test",
"embed",
"route",
];
for (let i = 0; i < KEYS.length; i++) {
const k = KEYS[i];
const matches = lower.split(k).length - 1;
v[i] = matches;
}
let sumsq = 0;
for (let i = 0; i < EMBEDDING_DIM; i++) sumsq += v[i] * v[i];
if (sumsq > 0) {
const inv = 1 / Math.sqrt(sumsq);
for (let i = 0; i < EMBEDDING_DIM; i++) v[i] *= inv;
}
return { vector: v, model: "stub-1024" };
};
}
async function probePgvector(): Promise<boolean> {
if (!HAS_DB) return false;
try {
const { db } = await import("../db");
const { codeEmbeddings } = await import("../db/schema");
const { eq } = await import("drizzle-orm");
const fakeRepoId = "00000000-0000-0000-0000-000000000000";
await db
.select({ id: codeEmbeddings.id })
.from(codeEmbeddings)
.where(eq(codeEmbeddings.repositoryId, fakeRepoId))
.limit(1);
return true;
} catch {
return false;
}
}
describe("semantic-index — pure helpers", () => {
it("fallbackEmbed returns a 1024-dim vector", () => {
const v = __test.fallbackEmbed("hello world function getUser");
expect(v.length).toBe(EMBEDDING_DIM);
});
it("fallbackEmbed is deterministic", () => {
const a = __test.fallbackEmbed("function indexFiles()");
const b = __test.fallbackEmbed("function indexFiles()");
expect(a).toEqual(b);
});
it("fallbackEmbed produces different vectors for different inputs", () => {
const a = __test.fallbackEmbed("database connection pool");
const b = __test.fallbackEmbed("react component render hook");
let differ = false;
for (let i = 0; i < EMBEDDING_DIM; i++) {
if (Math.abs(a[i] - b[i]) > 1e-9) {
differ = true;
break;
}
}
expect(differ).toBe(true);
});
it("deriveBlobSha is deterministic + 64 hex chars", async () => {
const a = await __test.deriveBlobSha("hello world");
const b = await __test.deriveBlobSha("hello world");
expect(a).toBe(b);
expect(/^[0-9a-f]{64}$/.test(a)).toBe(true);
});
it("MAX_FILES_PER_PUSH is the documented cap (~50)", () => {
expect(__test.MAX_FILES_PER_PUSH).toBeGreaterThanOrEqual(20);
expect(__test.MAX_FILES_PER_PUSH).toBeLessThanOrEqual(200);
});
});
describe("embedOne — test seam", () => {
it("respects __setEmbedderForTests override", async () => {
__setEmbedderForTests(async () => ({
vector: new Array(EMBEDDING_DIM).fill(0.001),
model: "fake-model",
}));
const out = await embedOne("anything", "document");
expect(out.model).toBe("fake-model");
expect(out.vector.length).toBe(EMBEDDING_DIM);
expect(out.vector[0]).toBe(0.001);
__setEmbedderForTests(null);
});
it("falls back to the deterministic embedder when no key + no override", async () => {
delete process.env.VOYAGE_API_KEY;
const out = await embedOne("hello world", "document");
expect(out.vector.length).toBe(EMBEDDING_DIM);
expect(out.model).toBe(__test.FALLBACK_MODEL);
});
});
describe("indexChangedFiles — graceful no-ops", () => {
it("returns 0/0 for empty path list", async () => {
const out = await indexChangedFiles({
repositoryId: "00000000-0000-0000-0000-000000000000",
ownerName: "nobody",
repoName: "nothing",
commitSha: "0000000000000000000000000000000000000000",
changedPaths: [],
});
expect(out.indexed).toBe(0);
});
it("returns 0/0 for empty repositoryId", async () => {
const out = await indexChangedFiles({
repositoryId: "",
ownerName: "x",
repoName: "y",
commitSha: "deadbeef",
changedPaths: ["src/foo.ts"],
});
expect(out.indexed).toBe(0);
});
it("filters out non-code files before doing any work", async () => {
__setEmbedderForTests(makeStubEmbedder());
const out = await indexChangedFiles({
repositoryId: "00000000-0000-0000-0000-000000000000",
ownerName: "nobody",
repoName: "nothing",
commitSha: "0000000000000000000000000000000000000000",
changedPaths: ["LICENSE", "image.png", "binary.zip"],
});
expect(out.indexed).toBe(0);
__setEmbedderForTests(null);
});
});
describe("searchSemantic — graceful no-ops", () => {
it("returns [] for empty query", async () => {
const out = await searchSemantic({
repositoryId: "00000000-0000-0000-0000-000000000000",
query: "",
});
expect(out).toEqual([]);
});
it("returns [] for empty repositoryId", async () => {
const out = await searchSemantic({
repositoryId: "",
query: "hello",
});
expect(out).toEqual([]);
});
it("clamps limit to [1, 100]", async () => {
const a = await searchSemantic({
repositoryId: "",
query: "hi",
limit: 0,
});
const b = await searchSemantic({
repositoryId: "",
query: "hi",
limit: 999999,
});
expect(a).toEqual([]);
expect(b).toEqual([]);
});
});
describe("GET /api/v2/repos/:o/:r/semantic-search — validation", () => {
it("returns 404 for a nonexistent repo (or 500 when no DB)", async () => {
const res = await app.request(
"/api/v2/repos/nobody/nothing/semantic-search?q=foo"
);
expect([404, 500]).toContain(res.status);
});
it("returns 404 (or 500 without DB) when called without ?q on a missing repo", async () => {
const res = await app.request(
"/api/v2/repos/nobody/nothing/semantic-search"
);
expect([404, 500]).toContain(res.status);
});
});
describe.skipIf(!HAS_DB)("semantic-index — DB-backed flows", () => {
it.skipIf(!HAS_DB)("upserts a row per file and ranks by similarity", async () => {
if (!HAS_PGVECTOR) {
return;
}
const { db } = await import("../db");
const { users, repositories, codeEmbeddings } = await import(
"../db/schema"
);
const { eq, and } = await import("drizzle-orm");
const stamp = randomBytes(4).toString("hex");
const username = `semuser-${stamp}`;
const reponame = `semrepo-${stamp}`;
const [u] = await db
.insert(users)
.values({
username,
email: `${username}@test.local`,
passwordHash: "x",
})
.returning();
if (!u) return;
const sha = await seedRepo(username, reponame, {
"src/fetch.ts": "export function fetchData() { return fetch('/api'); }\n",
"src/db.ts": "export function connectDatabase() { /* database pool */ }\n",
});
const [r] = await db
.insert(repositories)
.values({
name: reponame,
ownerId: u.id,
diskPath: getRepoPath(username, reponame),
defaultBranch: "main",
})
.returning();
if (!r) return;
__setEmbedderForTests(makeStubEmbedder());
const out = await indexChangedFiles({
repositoryId: r.id,
ownerName: username,
repoName: reponame,
commitSha: sha,
changedPaths: ["src/fetch.ts", "src/db.ts"],
});
expect(out.indexed).toBe(2);
const rows = await db
.select({
path: codeEmbeddings.filePath,
snippet: codeEmbeddings.contentSnippet,
})
.from(codeEmbeddings)
.where(eq(codeEmbeddings.repositoryId, r.id));
expect(rows.length).toBe(2);
const paths = rows.map((r) => r.path).sort();
expect(paths).toEqual(["src/db.ts", "src/fetch.ts"]);
for (const row of rows) {
expect(row.snippet.length).toBeGreaterThan(0);
expect(row.snippet.length).toBeLessThanOrEqual(500);
}
const hits = await searchSemantic({
repositoryId: r.id,
query: "fetch data",
limit: 5,
});
expect(hits.length).toBeGreaterThanOrEqual(1);
expect(hits[0].filePath).toBe("src/fetch.ts");
const hits2 = await searchSemantic({
repositoryId: r.id,
query: "database connection",
limit: 5,
});
expect(hits2.length).toBeGreaterThanOrEqual(1);
expect(hits2[0].filePath).toBe("src/db.ts");
const out2 = await indexChangedFiles({
repositoryId: r.id,
ownerName: username,
repoName: reponame,
commitSha: sha,
changedPaths: ["src/fetch.ts", "src/db.ts"],
});
expect(out2.indexed).toBe(2);
const rowsAfter = await db
.select({ id: codeEmbeddings.id })
.from(codeEmbeddings)
.where(eq(codeEmbeddings.repositoryId, r.id));
expect(rowsAfter.length).toBe(2);
await db.delete(codeEmbeddings).where(eq(codeEmbeddings.repositoryId, r.id));
await db
.delete(repositories)
.where(and(eq(repositories.ownerId, u.id), eq(repositories.name, reponame)));
await db.delete(users).where(eq(users.id, u.id));
__setEmbedderForTests(null);
});
it.skipIf(!HAS_DB)(
"GET /api/v2/repos/:o/:r/semantic-search returns the indexed hits",
async () => {
if (!HAS_PGVECTOR) return;
const { db } = await import("../db");
const { users, repositories, codeEmbeddings } = await import(
"../db/schema"
);
const { eq, and } = await import("drizzle-orm");
const stamp = randomBytes(4).toString("hex");
const username = `semapi-${stamp}`;
const reponame = `semapi-${stamp}`;
const [u] = await db
.insert(users)
.values({
username,
email: `${username}@test.local`,
passwordHash: "x",
})
.returning();
if (!u) return;
const sha = await seedRepo(username, reponame, {
"src/main.ts": "export function fetchUserData() { return fetch('/u'); }\n",
});
const [r] = await db
.insert(repositories)
.values({
name: reponame,
ownerId: u.id,
diskPath: getRepoPath(username, reponame),
defaultBranch: "main",
isPrivate: false,
})
.returning();
if (!r) return;
__setEmbedderForTests(makeStubEmbedder());
await indexChangedFiles({
repositoryId: r.id,
ownerName: username,
repoName: reponame,
commitSha: sha,
changedPaths: ["src/main.ts"],
});
const res = await app.request(
`/api/v2/repos/${username}/${reponame}/semantic-search?q=fetch`
);
expect(res.status).toBe(200);
const body = (await res.json()) as Array<{
file_path: string;
snippet: string;
score: number;
blob_sha: string;
}>;
expect(Array.isArray(body)).toBe(true);
expect(body.length).toBeGreaterThanOrEqual(1);
expect(body[0].file_path).toBe("src/main.ts");
expect(typeof body[0].score).toBe("number");
expect(typeof body[0].blob_sha).toBe("string");
await db
.delete(codeEmbeddings)
.where(eq(codeEmbeddings.repositoryId, r.id));
await db
.delete(repositories)
.where(
and(eq(repositories.ownerId, u.id), eq(repositories.name, reponame))
);
await db.delete(users).where(eq(users.id, u.id));
__setEmbedderForTests(null);
}
);
});
|