Pre-launch — Gluecron is in final validation. Public signups and git hosting for non-owner users open after launch review.
CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
claude/adoring-hopper-5x74bqclaude/affectionate-feynman-ykrf1hclaude/architecture-audit-design-wxprenclaude/build-status-update-3MXsfclaude/charming-meitner-mllb5rclaude/compare-gate-gluecron-s4mFQclaude/confident-faraday-tikcwbclaude/continue-work-XMTlIclaude/crontech-gluecron-deploy-7MIECclaude/crontech-platform-setup-SeKfwclaude/design-2026claude/ecstatic-ptolemy-jMdigclaude/enhance-github-integration-QNHdGclaude/fix-aa-loop-issue-PonMQclaude/fix-actions-and-processclaude/fix-desktop-errors-XqoW8claude/fix-red-workflowsclaude/fix-website-access-6FKJNclaude/gatetest-integration-hardeningclaude/github-audit-improvements-bDFr9claude/gluecron-launch-status-FoMRlclaude/hopeful-lamport-olfCTclaude/issue-to-pr-and-protectionsclaude/jolly-heisenberg-2sg1Qclaude/launch-preparation-QmTb6claude/new-session-xk1l7claude/plan-platform-architecture-kkN4yclaude/platform-analysis-roadmap-1nUGLclaude/platform-launch-assessment-8dWV8claude/polish-platform-release-AeDrUclaude/resume-previous-work-KzyLwclaude/review-crontech-handoff-qYEVqclaude/review-project-completeness-lHhS2claude/review-readme-docs-ulqPKclaude/serene-edison-rj87weclaude/setup-multi-repo-dev-BCwNQclaude/ship-fixes-and-tests-Jvz1cclaude/site-audit-competitive-pctlwgclaude/site-migration-vercel-XstpKclaude/standalone-product-repos-XHFTDcopilot/feat-smart-empty-states-keyboard-first-enhancementcopilot/feat-smart-morning-digest-review-context-restorecopilot/fix-and-process-workflowscopilot/update-ai-powered-code-reviewfeat/debt-mapfeat/push-policy-codeowners-hardeningfeat/smart-digest-contextfeat/stage-impactfeat/t1-secret-migrationfeat/u-polishfeat/w-self-hostfeat/w2-claude-configfix/agent-journey-orphan-sweepgatetest/auto-fix-1776586424172gatetest/auto-fix-1776586534814gatetest/auto-fix-1776590685143gatetest/auto-fix-1776590808199mainops/redeploy-retriggerstyle/dxt-cta-themeworktree-agent-a3377aad30d55da26worktree-agent-a7ef607b7ee1d6c74
personal-semantic.test.ts17.3 KB · 582 lines
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
/**
 * Tests for src/lib/personal-semantic.ts — cross-repo semantic search
 * over the union of repos a user has access to.
 *
 * Layered:
 *
 *   1. Pure helpers / opt-in gate (no DB-specific shapes).
 *      Covered by short-circuit assertions on missing inputs.
 *
 *   2. DB-backed pipeline — gated on HAS_DB.
 *      Critical security tests live here:
 *        - Refusal when the opt-in flag is OFF (the privacy contract).
 *        - Owned-repo hits surface; non-owned repos that the user has
 *          no collaborator row for are NEVER surfaced.
 *        - Cross-user leak prevention: a hit indexed for user-B's
 *          private repo must not appear in user-A's results.
 *
 * The embedder seam from semantic-index is used to make vectors
 * deterministic so the test asserts on file_path / repo_name shape rather
 * than on cosine-score ordering (which depends on pgvector being
 * available).
 */

import {
  afterAll,
  afterEach,
  beforeAll,
  beforeEach,
  describe,
  expect,
  it,
} from "bun:test";
import { join } from "path";
import { mkdir, rm } from "fs/promises";
import { randomBytes } from "crypto";

import {
  isPersonalSemanticEnabled,
  searchAcrossAllReposForUser,
  searchPersonalSemantic,
  setPersonalSemanticEnabled,
} from "../lib/personal-semantic";
import {
  __setEmbedderForTests,
  EMBEDDING_DIM,
} from "../lib/semantic-index";
import { initBareRepo, getRepoPath } from "../git/repository";

const HAS_DB = Boolean(process.env.DATABASE_URL);

const TEST_REPOS = join(
  import.meta.dir,
  "../../.test-repos-personal-semantic-" + Date.now()
);

beforeAll(async () => {
  process.env.GIT_REPOS_PATH = TEST_REPOS;
  process.env.GLUECRON_SEMANTIC_CACHE_DIR = join(TEST_REPOS, "_cache");
  await rm(TEST_REPOS, { recursive: true, force: true });
  await mkdir(TEST_REPOS, { recursive: true });
});

afterAll(async () => {
  __setEmbedderForTests(null);
  await rm(TEST_REPOS, { recursive: true, force: true });
});

beforeEach(() => {
  __setEmbedderForTests(null);
});

afterEach(() => {
  __setEmbedderForTests(null);
});

// ---------------------------------------------------------------------------
// 1. Pure short-circuits — no DB.
// ---------------------------------------------------------------------------

describe("personal-semantic — short-circuits", () => {
  it("returns [] for empty userId", async () => {
    const out = await searchPersonalSemantic({ userId: "", query: "foo" });
    expect(out).toEqual([]);
  });

  it("returns [] for empty query", async () => {
    const out = await searchPersonalSemantic({
      userId: "00000000-0000-0000-0000-000000000000",
      query: "",
    });
    expect(out).toEqual([]);
  });

  it("alias searchAcrossAllReposForUser is identical contract", async () => {
    const out = await searchAcrossAllReposForUser({
      userId: "",
      query: "foo",
    });
    expect(out).toEqual([]);
  });

  it("isPersonalSemanticEnabled returns false for empty id", async () => {
    expect(await isPersonalSemanticEnabled("")).toBe(false);
  });
});

// ---------------------------------------------------------------------------
// 2. DB-backed pipeline.
// ---------------------------------------------------------------------------

describe.skipIf(!HAS_DB)("personal-semantic — DB-backed", () => {
  it.skipIf(!HAS_DB)(
    "refuses to return rows when the opt-in flag is OFF",
    async () => {
      const { db } = await import("../db");
      const { users, repositories, codeEmbeddings } = await import(
        "../db/schema"
      );
      const { eq } = await import("drizzle-orm");

      const stamp = randomBytes(4).toString("hex");
      const username = `psem-off-${stamp}`;
      const reponame = `psem-off-${stamp}`;

      const [u] = await db
        .insert(users)
        .values({
          username,
          email: `${username}@test.local`,
          passwordHash: "x",
          personalSemanticIndexEnabled: false,
        })
        .returning();
      if (!u) return;

      await initBareRepo(username, reponame);
      const [r] = await db
        .insert(repositories)
        .values({
          name: reponame,
          ownerId: u.id,
          diskPath: getRepoPath(username, reponame),
          defaultBranch: "main",
        })
        .returning();
      if (!r) return;

      // Plant an embedding row; with opt-in OFF the search must not
      // surface it even though the user owns the repo.
      const fakeVec = new Array<number>(EMBEDDING_DIM).fill(0);
      fakeVec[0] = 1;
      try {
        await db.insert(codeEmbeddings).values({
          repositoryId: r.id,
          filePath: "src/secret.ts",
          blobSha: "aa11",
          commitSha: "aa11",
          contentSnippet: "// SECRET KEY",
          embedding: fakeVec,
          embeddingModel: "stub",
        });
      } catch {
        /* pgvector may not exist; the opt-in refusal is still meaningful
           because it short-circuits BEFORE the cosine ORDER BY runs. */
      }

      __setEmbedderForTests(async () => ({
        vector: fakeVec,
        model: "stub-1024",
      }));

      const hits = await searchPersonalSemantic({
        userId: u.id,
        query: "secret",
      });
      expect(hits).toEqual([]);

      // Now flip on and verify the hit does surface — proves the refusal
      // above is the flag, not a side-effect of missing data.
      await setPersonalSemanticEnabled(u.id, true);
      const after = await searchPersonalSemantic({
        userId: u.id,
        query: "secret",
      });
      // pgvector may not be installed; allow either an empty result or
      // the planted row. The point of THIS assertion is that we no
      // longer SHORT-CIRCUIT — DB-level behaviour is allowed to be empty.
      expect(Array.isArray(after)).toBe(true);
      if (after.length) {
        expect(after[0].repoName).toBe(`${username}/${reponame}`);
        expect(after[0].filePath).toBe("src/secret.ts");
      }

      // Cleanup.
      try {
        await db
          .delete(codeEmbeddings)
          .where(eq(codeEmbeddings.repositoryId, r.id));
      } catch {
        /* may not exist */
      }
      await db.delete(repositories).where(eq(repositories.id, r.id));
      await db.delete(users).where(eq(users.id, u.id));
    }
  );

  it.skipIf(!HAS_DB)(
    "search returns results across multiple owned repos",
    async () => {
      const { db } = await import("../db");
      const { users, repositories, codeEmbeddings } = await import(
        "../db/schema"
      );
      const { eq, inArray } = await import("drizzle-orm");

      const stamp = randomBytes(4).toString("hex");
      const username = `psem-multi-${stamp}`;

      const [u] = await db
        .insert(users)
        .values({
          username,
          email: `${username}@test.local`,
          passwordHash: "x",
          personalSemanticIndexEnabled: true,
        })
        .returning();
      if (!u) return;

      const repoA = `psem-multi-a-${stamp}`;
      const repoB = `psem-multi-b-${stamp}`;
      await initBareRepo(username, repoA);
      await initBareRepo(username, repoB);
      const [rA] = await db
        .insert(repositories)
        .values({
          name: repoA,
          ownerId: u.id,
          diskPath: getRepoPath(username, repoA),
          defaultBranch: "main",
        })
        .returning();
      const [rB] = await db
        .insert(repositories)
        .values({
          name: repoB,
          ownerId: u.id,
          diskPath: getRepoPath(username, repoB),
          defaultBranch: "main",
        })
        .returning();
      if (!rA || !rB) return;

      const fakeVec = new Array<number>(EMBEDDING_DIM).fill(0);
      fakeVec[0] = 1;
      let inserted = false;
      try {
        await db.insert(codeEmbeddings).values([
          {
            repositoryId: rA.id,
            filePath: "src/a.ts",
            blobSha: "aaa1",
            commitSha: "aaa1",
            contentSnippet: "// repo a snippet",
            embedding: fakeVec,
            embeddingModel: "stub",
          },
          {
            repositoryId: rB.id,
            filePath: "src/b.ts",
            blobSha: "bbb1",
            commitSha: "bbb1",
            contentSnippet: "// repo b snippet",
            embedding: fakeVec,
            embeddingModel: "stub",
          },
        ]);
        inserted = true;
      } catch {
        /* pgvector missing — we'll skip the surface assertion below */
      }

      __setEmbedderForTests(async () => ({
        vector: fakeVec,
        model: "stub-1024",
      }));

      const hits = await searchPersonalSemantic({
        userId: u.id,
        query: "snippet",
      });
      expect(Array.isArray(hits)).toBe(true);

      // When pgvector is available, both repos should show up — they're
      // both owned by the user, so the union contains both.
      if (inserted && hits.length) {
        const repoNames = new Set(hits.map((h) => h.repoName));
        expect(repoNames.size).toBeGreaterThanOrEqual(1);
        for (const h of hits) {
          expect(typeof h.repoName).toBe("string");
          expect(h.repoName.startsWith(`${username}/`)).toBe(true);
        }
      }

      // Cleanup.
      try {
        await db
          .delete(codeEmbeddings)
          .where(inArray(codeEmbeddings.repositoryId, [rA.id, rB.id]));
      } catch {
        /* may not exist */
      }
      await db
        .delete(repositories)
        .where(inArray(repositories.id, [rA.id, rB.id]));
      await db.delete(users).where(eq(users.id, u.id));
    }
  );

  it.skipIf(!HAS_DB)(
    "search EXCLUDES repos the user has no access to",
    async () => {
      const { db } = await import("../db");
      const { users, repositories, codeEmbeddings } = await import(
        "../db/schema"
      );
      const { eq, inArray } = await import("drizzle-orm");

      const stamp = randomBytes(4).toString("hex");
      const userA = `psem-exclA-${stamp}`;
      const userB = `psem-exclB-${stamp}`;

      const [uA] = await db
        .insert(users)
        .values({
          username: userA,
          email: `${userA}@test.local`,
          passwordHash: "x",
          personalSemanticIndexEnabled: true,
        })
        .returning();
      const [uB] = await db
        .insert(users)
        .values({
          username: userB,
          email: `${userB}@test.local`,
          passwordHash: "x",
        })
        .returning();
      if (!uA || !uB) return;

      // User B owns a private repo. User A has NO collaborator row for it.
      const repoB = `psem-excl-${stamp}`;
      await initBareRepo(userB, repoB);
      const [rB] = await db
        .insert(repositories)
        .values({
          name: repoB,
          ownerId: uB.id,
          diskPath: getRepoPath(userB, repoB),
          defaultBranch: "main",
          isPrivate: true,
        })
        .returning();
      if (!rB) return;

      const fakeVec = new Array<number>(EMBEDDING_DIM).fill(0);
      fakeVec[0] = 1;
      try {
        await db.insert(codeEmbeddings).values({
          repositoryId: rB.id,
          filePath: "src/foreign.ts",
          blobSha: "cccc",
          commitSha: "cccc",
          contentSnippet: "// USER B's PRIVATE CODE",
          embedding: fakeVec,
          embeddingModel: "stub",
        });
      } catch {
        /* pgvector missing — refusal must still hold via the IN ([]) path */
      }

      __setEmbedderForTests(async () => ({
        vector: fakeVec,
        model: "stub-1024",
      }));

      // User A has no repos of their own and no collaborator rows.
      // The accessible-repo-set must be empty, so search returns [] without
      // EVER consulting User B's embedding row.
      const hits = await searchPersonalSemantic({
        userId: uA.id,
        query: "private",
      });
      expect(hits).toEqual([]);

      // Even if User A asks for the exact snippet text, the WHERE clause
      // gates them out.
      const hits2 = await searchPersonalSemantic({
        userId: uA.id,
        query: "USER B's PRIVATE CODE",
      });
      expect(hits2).toEqual([]);

      // Cleanup.
      try {
        await db
          .delete(codeEmbeddings)
          .where(inArray(codeEmbeddings.repositoryId, [rB.id]));
      } catch {
        /* may not exist */
      }
      await db.delete(repositories).where(eq(repositories.id, rB.id));
      await db.delete(users).where(eq(users.id, uA.id));
      await db.delete(users).where(eq(users.id, uB.id));
    }
  );

  it.skipIf(!HAS_DB)(
    "cross-user content leak prevention — User A's results never contain User B's repo data",
    async () => {
      // This test is the load-bearing security assertion. We give User A
      // one owned repo with data, and User B one separate owned repo with
      // distinctively different data. Both have the opt-in flag on. A's
      // search must only see A's repo; B's results must not appear in A's.
      const { db } = await import("../db");
      const { users, repositories, codeEmbeddings } = await import(
        "../db/schema"
      );
      const { eq, inArray } = await import("drizzle-orm");

      const stamp = randomBytes(4).toString("hex");
      const userA = `psem-leakA-${stamp}`;
      const userB = `psem-leakB-${stamp}`;

      const [uA] = await db
        .insert(users)
        .values({
          username: userA,
          email: `${userA}@test.local`,
          passwordHash: "x",
          personalSemanticIndexEnabled: true,
        })
        .returning();
      const [uB] = await db
        .insert(users)
        .values({
          username: userB,
          email: `${userB}@test.local`,
          passwordHash: "x",
          personalSemanticIndexEnabled: true,
        })
        .returning();
      if (!uA || !uB) return;

      const repoA = `psem-leak-a-${stamp}`;
      const repoB = `psem-leak-b-${stamp}`;
      await initBareRepo(userA, repoA);
      await initBareRepo(userB, repoB);
      const [rA] = await db
        .insert(repositories)
        .values({
          name: repoA,
          ownerId: uA.id,
          diskPath: getRepoPath(userA, repoA),
          defaultBranch: "main",
        })
        .returning();
      const [rB] = await db
        .insert(repositories)
        .values({
          name: repoB,
          ownerId: uB.id,
          diskPath: getRepoPath(userB, repoB),
          defaultBranch: "main",
        })
        .returning();
      if (!rA || !rB) return;

      const fakeVec = new Array<number>(EMBEDDING_DIM).fill(0);
      fakeVec[0] = 1;
      try {
        await db.insert(codeEmbeddings).values([
          {
            repositoryId: rA.id,
            filePath: "src/owned-by-a.ts",
            blobSha: "aaaa",
            commitSha: "aaaa",
            contentSnippet: "// A's code",
            embedding: fakeVec,
            embeddingModel: "stub",
          },
          {
            repositoryId: rB.id,
            filePath: "src/owned-by-b.ts",
            blobSha: "bbbb",
            commitSha: "bbbb",
            contentSnippet: "// B's code",
            embedding: fakeVec,
            embeddingModel: "stub",
          },
        ]);
      } catch {
        /* pgvector missing — the next assertions still hold via the
           empty-repo-set short-circuit / IN clause */
      }

      __setEmbedderForTests(async () => ({
        vector: fakeVec,
        model: "stub-1024",
      }));

      const aHits = await searchPersonalSemantic({
        userId: uA.id,
        query: "code",
      });
      // Every hit must be from a repo A owns. The file owned-by-b.ts
      // must never appear; the repo name must never include userB.
      for (const h of aHits) {
        expect(h.ownerName).toBe(userA);
        expect(h.repoName).toBe(`${userA}/${repoA}`);
        expect(h.filePath).not.toBe("src/owned-by-b.ts");
      }

      const bHits = await searchPersonalSemantic({
        userId: uB.id,
        query: "code",
      });
      for (const h of bHits) {
        expect(h.ownerName).toBe(userB);
        expect(h.repoName).toBe(`${userB}/${repoB}`);
        expect(h.filePath).not.toBe("src/owned-by-a.ts");
      }

      // Cleanup.
      try {
        await db
          .delete(codeEmbeddings)
          .where(inArray(codeEmbeddings.repositoryId, [rA.id, rB.id]));
      } catch {
        /* may not exist */
      }
      await db
        .delete(repositories)
        .where(inArray(repositories.id, [rA.id, rB.id]));
      await db.delete(users).where(eq(users.id, uA.id));
      await db.delete(users).where(eq(users.id, uB.id));
    }
  );

  it.skipIf(!HAS_DB)(
    "setPersonalSemanticEnabled flips the flag and isPersonalSemanticEnabled reads it",
    async () => {
      const { db } = await import("../db");
      const { users } = await import("../db/schema");
      const { eq } = await import("drizzle-orm");

      const stamp = randomBytes(4).toString("hex");
      const username = `psem-flag-${stamp}`;
      const [u] = await db
        .insert(users)
        .values({
          username,
          email: `${username}@test.local`,
          passwordHash: "x",
        })
        .returning();
      if (!u) return;

      expect(await isPersonalSemanticEnabled(u.id)).toBe(false);
      const r1 = await setPersonalSemanticEnabled(u.id, true);
      expect(r1).toBe(true);
      expect(await isPersonalSemanticEnabled(u.id)).toBe(true);

      const r2 = await setPersonalSemanticEnabled(u.id, false);
      expect(r2).toBe(false);
      expect(await isPersonalSemanticEnabled(u.id)).toBe(false);

      await db.delete(users).where(eq(users.id, u.id));
    }
  );
});