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
semantic-search.tsx10.0 KB · 325 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
/**
 * Block D1 — Semantic code search UI + reindex trigger.
 *
 *   GET  /:owner/:repo/search/semantic?q=...      — results page (ILIKE parity)
 *   POST /:owner/:repo/search/semantic/reindex    — owner-only, fire-and-forget
 *
 * Intentionally tolerates a missing DB / missing repo / missing index so the
 * page is always navigable. When there's no index yet, the page shows a
 * "Build index" CTA pointing at the reindex endpoint.
 */

import { Hono } from "hono";
import { eq, and, desc } from "drizzle-orm";
import { db } from "../db";
import { repositories, users, codeChunks } from "../db/schema";
import { Layout } from "../views/layout";
import { RepoHeader } from "../views/components";
import { IssueNav } from "./issues";
import { softAuth, requireAuth } from "../middleware/auth";
import type { AuthEnv } from "../middleware/auth";
import {
  getDefaultBranch,
  resolveRef,
  repoExists,
} from "../git/repository";
import {
  indexRepository,
  searchRepository,
  isEmbeddingsProviderAvailable,
} from "../lib/semantic-search";

const semanticSearch = new Hono<AuthEnv>();
semanticSearch.use("*", softAuth);

async function resolveRepo(ownerName: string, repoName: string) {
  try {
    const [owner] = await db
      .select()
      .from(users)
      .where(eq(users.username, ownerName))
      .limit(1);
    if (!owner) return null;
    const [repo] = await db
      .select()
      .from(repositories)
      .where(
        and(
          eq(repositories.ownerId, owner.id),
          eq(repositories.name, repoName)
        )
      )
      .limit(1);
    if (!repo) return null;
    return { owner, repo };
  } catch {
    return null;
  }
}

function NotFound({ user }: { user: any }) {
  return (
    <Layout title="Not Found" user={user}>
      <div class="empty-state">
        <h2>Repository not found</h2>
        <p>No such repository, or you don't have access.</p>
      </div>
    </Layout>
  );
}

semanticSearch.get("/:owner/:repo/search/semantic", async (c) => {
  const { owner: ownerName, repo: repoName } = c.req.param();
  const user = c.get("user");
  const q = (c.req.query("q") || "").trim();
  const flash = c.req.query("flash");

  const resolved = await resolveRepo(ownerName, repoName);
  if (!resolved) {
    return c.html(<NotFound user={user} />, 404);
  }
  const { repo } = resolved;

  // Figure out last-indexed state (chunk count + most recent createdAt).
  let indexedCount = 0;
  let lastIndexedAt: Date | null = null;
  let indexedCommitSha: string | null = null;
  try {
    // Grab the newest chunk row for metadata (sha + createdAt).
    const [newest] = await db
      .select({
        createdAt: codeChunks.createdAt,
        commitSha: codeChunks.commitSha,
      })
      .from(codeChunks)
      .where(eq(codeChunks.repositoryId, repo.id))
      .orderBy(desc(codeChunks.createdAt))
      .limit(1);
    if (newest) {
      lastIndexedAt = newest.createdAt as unknown as Date;
      indexedCommitSha = newest.commitSha || null;
      // Rough count for the UI blurb — order of magnitude is fine.
      const rows = await db
        .select({ id: codeChunks.id })
        .from(codeChunks)
        .where(eq(codeChunks.repositoryId, repo.id))
        .limit(5000);
      indexedCount = rows.length;
    }
  } catch {
    // DB unavailable — show the page anyway so the URL always resolves.
  }

  let hits: Awaited<ReturnType<typeof searchRepository>> = [];
  if (q && indexedCount > 0) {
    try {
      hits = await searchRepository({
        repositoryId: repo.id,
        query: q,
        limit: 20,
      });
    } catch {
      hits = [];
    }
  }

  const providers = isEmbeddingsProviderAvailable();
  const providerLabel = providers.voyage
    ? "Voyage voyage-code-3"
    : "lexical fallback (512-dim)";

  const isOwner = !!user && user.id === repo.ownerId;
  const refForLinks = indexedCommitSha || repo.defaultBranch || "HEAD";

  return c.html(
    <Layout title={`Semantic search — ${ownerName}/${repoName}`} user={user}>
      <RepoHeader owner={ownerName} repo={repoName} />
      <IssueNav owner={ownerName} repo={repoName} active="code" />

      <div style="display: flex; justify-content: space-between; align-items: baseline; margin-bottom: 12px">
        <h2 style="margin: 0">Semantic search</h2>
        <div class="meta" style="font-size: 12px">
          Provider: <strong>{providerLabel}</strong>
        </div>
      </div>

      {flash && (
        <div class="auth-success" style="margin-bottom: 16px">
          {decodeURIComponent(flash)}
        </div>
      )}

      <form
        method="get"
        action={`/${ownerName}/${repoName}/search/semantic`}
        style="margin-bottom: 16px"
      >
        <input
          type="search"
          name="q"
          value={q}
          placeholder="Ask a question or describe what you're looking for…"
          style="width: 100%; padding: 10px 14px; background: var(--bg); border: 1px solid var(--border); border-radius: var(--radius); color: var(--text); font-size: 14px"
          autofocus
        />
      </form>

      {indexedCount === 0 ? (
        <div class="empty-state">
          <h3>No index yet</h3>
          <p>
            This repository hasn't been indexed for semantic search. Build the
            index to enable AI-powered code lookup.
          </p>
          {isOwner ? (
            <form
              method="post"
              action={`/${ownerName}/${repoName}/search/semantic/reindex`}
              style="margin-top: 12px"
            >
              <button type="submit" class="btn btn-primary">
                Build index
              </button>
            </form>
          ) : (
            <p class="meta" style="margin-top: 8px">
              Only the repository owner can trigger indexing.
            </p>
          )}
        </div>
      ) : (
        <>
          <div
            class="meta"
            style="font-size: 12px; margin-bottom: 12px; display: flex; justify-content: space-between; align-items: center"
          >
            <span>
              {indexedCount} chunk{indexedCount === 1 ? "" : "s"} indexed
              {lastIndexedAt && (
                <>
                  {" · last indexed "}
                  {new Date(lastIndexedAt).toLocaleString()}
                </>
              )}
            </span>
            {isOwner && (
              <form
                method="post"
                action={`/${ownerName}/${repoName}/search/semantic/reindex`}
                style="display: inline"
              >
                <button type="submit" class="btn btn-sm">
                  Reindex
                </button>
              </form>
            )}
          </div>

          {!q ? (
            <div class="empty-state">
              <p>Type a query to search across this repo's code.</p>
            </div>
          ) : hits.length === 0 ? (
            <div class="empty-state">
              <p>No results for "{q}"</p>
            </div>
          ) : (
            <div class="panel">
              {hits.map((h) => {
                const href = `/${ownerName}/${repoName}/blob/${refForLinks}/${h.path}#L${h.startLine}`;
                const preview =
                  h.content.length > 600
                    ? h.content.slice(0, 600) + "\n…"
                    : h.content;
                return (
                  <div class="panel-item" style="flex-direction: column; align-items: stretch">
                    <div
                      style="display: flex; justify-content: space-between; align-items: baseline; margin-bottom: 6px"
                    >
                      <a href={href} style="font-weight: 600">
                        {h.path}
                      </a>
                      <span class="meta" style="font-size: 11px">
                        lines {h.startLine}–{h.endLine} · score{" "}
                        {h.score.toFixed(3)}
                      </span>
                    </div>
                    <pre
                      style="margin: 0; padding: 8px; background: var(--bg); border: 1px solid var(--border); border-radius: 4px; font-size: 12px; overflow-x: auto; white-space: pre-wrap"
                    >
                      {preview}
                    </pre>
                  </div>
                );
              })}
            </div>
          )}
        </>
      )}
    </Layout>
  );
});

// Owner-only: rebuild the index. Fire-and-forget so the UI doesn't block on
// potentially multi-minute work. Always redirects.
semanticSearch.post(
  "/:owner/:repo/search/semantic/reindex",
  requireAuth,
  async (c) => {
    const { owner: ownerName, repo: repoName } = c.req.param();
    const user = c.get("user")!;

    const resolved = await resolveRepo(ownerName, repoName);
    if (!resolved) {
      return c.redirect(`/${ownerName}/${repoName}`);
    }
    const { repo } = resolved;

    if (repo.ownerId !== user.id) {
      return c.redirect(
        `/${ownerName}/${repoName}/search/semantic?flash=${encodeURIComponent(
          "Only the repository owner can trigger indexing."
        )}`
      );
    }

    // Resolve the commit sha at the default branch. If the repo has no
    // commits yet we bail with a friendly flash.
    let sha: string | null = null;
    try {
      if (await repoExists(ownerName, repoName)) {
        const branch =
          (await getDefaultBranch(ownerName, repoName)) ||
          repo.defaultBranch ||
          "main";
        sha = await resolveRef(ownerName, repoName, branch);
      }
    } catch {
      sha = null;
    }

    if (!sha) {
      return c.redirect(
        `/${ownerName}/${repoName}/search/semantic?flash=${encodeURIComponent(
          "Repository has no commits yet — nothing to index."
        )}`
      );
    }

    // Fire-and-forget. Errors are swallowed inside indexRepository.
    void indexRepository({
      owner: ownerName,
      repo: repoName,
      repositoryId: repo.id,
      commitSha: sha,
    });

    return c.redirect(
      `/${ownerName}/${repoName}/search/semantic?flash=${encodeURIComponent(
        "Indexing started — results will appear shortly."
      )}`
    );
  }
);

export default semanticSearch;