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
symbols.ts9.2 KB · 319 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
/**
 * Block I8 — Symbol / xref navigation.
 *
 * A pragmatic regex-based top-level symbol extractor. Runs per-language,
 * catches the common definition shapes (function / class / interface /
 * type / const). References are computed at lookup-time by grepping the
 * repository's tree for the symbol name, so this module persists only
 * definitions. Never throws into request path.
 */

import { and, eq } from "drizzle-orm";
import { db } from "../db";
import { codeSymbols, repositories, users } from "../db/schema";
import { getBlob, getTree, getDefaultBranch, resolveRef } from "../git/repository";
import type { CodeSymbol } from "../db/schema";
import type { GitTreeEntry } from "../git/repository";

export type SymbolKind =
  | "function"
  | "class"
  | "interface"
  | "type"
  | "const"
  | "variable";

export interface ExtractedSymbol {
  name: string;
  kind: SymbolKind;
  line: number;
  signature: string;
}

type Rule = { kind: SymbolKind; re: RegExp };

// ---------- Language detection ----------

const EXT_LANG: Record<string, string> = {
  ts: "ts",
  tsx: "ts",
  js: "ts",
  jsx: "ts",
  mjs: "ts",
  cjs: "ts",
  py: "py",
  rs: "rs",
  go: "go",
  rb: "rb",
  java: "java",
  kt: "kt",
  swift: "swift",
};

export function detectLanguage(path: string): string | null {
  const ext = path.split(".").pop()?.toLowerCase() || "";
  return EXT_LANG[ext] ?? null;
}

// ---------- Per-language rules ----------

const RULES: Record<string, Rule[]> = {
  ts: [
    {
      kind: "function",
      re: /^\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)/,
    },
    {
      kind: "function",
      re: /^\s*(?:export\s+)?const\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?\(/,
    },
    {
      kind: "function",
      re: /^\s*(?:export\s+)?const\s+([A-Za-z_$][\w$]*)\s*:\s*[^=]+=\s*(?:async\s*)?\(/,
    },
    {
      kind: "class",
      re: /^\s*(?:export\s+)?(?:default\s+)?(?:abstract\s+)?class\s+([A-Za-z_$][\w$]*)/,
    },
    {
      kind: "interface",
      re: /^\s*(?:export\s+)?interface\s+([A-Za-z_$][\w$]*)/,
    },
    {
      kind: "type",
      re: /^\s*(?:export\s+)?type\s+([A-Za-z_$][\w$]*)\s*=/,
    },
    {
      kind: "const",
      re: /^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*[:=]/,
    },
  ],
  py: [
    { kind: "function", re: /^\s*(?:async\s+)?def\s+([A-Za-z_][\w]*)\s*\(/ },
    { kind: "class", re: /^\s*class\s+([A-Za-z_][\w]*)\s*[:(]/ },
    { kind: "const", re: /^([A-Z_][A-Z0-9_]*)\s*=/ },
  ],
  rs: [
    { kind: "function", re: /^\s*(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?fn\s+([A-Za-z_][\w]*)/ },
    { kind: "class", re: /^\s*(?:pub(?:\([^)]*\))?\s+)?struct\s+([A-Za-z_][\w]*)/ },
    { kind: "interface", re: /^\s*(?:pub(?:\([^)]*\))?\s+)?trait\s+([A-Za-z_][\w]*)/ },
    { kind: "type", re: /^\s*(?:pub(?:\([^)]*\))?\s+)?type\s+([A-Za-z_][\w]*)\s*=/ },
    { kind: "const", re: /^\s*(?:pub(?:\([^)]*\))?\s+)?const\s+([A-Z_][A-Z0-9_]*)\s*:/ },
  ],
  go: [
    { kind: "function", re: /^\s*func(?:\s+\([^)]*\))?\s+([A-Za-z_][\w]*)\s*\(/ },
    { kind: "class", re: /^\s*type\s+([A-Za-z_][\w]*)\s+struct\b/ },
    { kind: "interface", re: /^\s*type\s+([A-Za-z_][\w]*)\s+interface\b/ },
    { kind: "type", re: /^\s*type\s+([A-Za-z_][\w]*)\s+\w/ },
    { kind: "const", re: /^\s*const\s+([A-Za-z_][\w]*)\s*=/ },
  ],
  rb: [
    { kind: "function", re: /^\s*def\s+(?:self\.)?([A-Za-z_][\w?!=]*)/ },
    { kind: "class", re: /^\s*class\s+([A-Z][\w]*)/ },
  ],
  java: [
    {
      kind: "class",
      re: /^\s*(?:public|private|protected)?\s*(?:abstract\s+|final\s+)?class\s+([A-Z][\w]*)/,
    },
    {
      kind: "interface",
      re: /^\s*(?:public|private|protected)?\s*interface\s+([A-Z][\w]*)/,
    },
  ],
  kt: [
    { kind: "function", re: /^\s*(?:public|private|internal)?\s*fun\s+([A-Za-z_][\w]*)/ },
    { kind: "class", re: /^\s*(?:public|private|internal)?\s*class\s+([A-Z][\w]*)/ },
  ],
  swift: [
    { kind: "function", re: /^\s*(?:public|private|fileprivate|internal)?\s*func\s+([A-Za-z_][\w]*)/ },
    { kind: "class", re: /^\s*(?:public|private|fileprivate|internal)?\s*class\s+([A-Z][\w]*)/ },
    { kind: "interface", re: /^\s*(?:public|private|fileprivate|internal)?\s*protocol\s+([A-Z][\w]*)/ },
  ],
};

// ---------- Extractor ----------

/** Pure — extract top-level symbol definitions from a single file. */
export function extractSymbols(
  content: string,
  lang: string
): ExtractedSymbol[] {
  const rules = RULES[lang];
  if (!rules) return [];
  const out: ExtractedSymbol[] = [];
  const seen = new Set<string>();
  const lines = content.split("\n");
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i];
    if (line.length > 500) continue; // skip minified lines
    for (const rule of rules) {
      const m = line.match(rule.re);
      if (m && m[1]) {
        const key = `${rule.kind}:${m[1]}:${i}`;
        if (seen.has(key)) continue;
        seen.add(key);
        out.push({
          name: m[1],
          kind: rule.kind,
          line: i + 1,
          signature: line.trim().slice(0, 240),
        });
        break; // one match per line
      }
    }
  }
  return out;
}

// ---------- Indexer ----------

const INDEXABLE_MAX_BYTES = 1_000_000; // skip files over 1MB
const MAX_FILES = 2_000; // cap per reindex

async function walkCodePaths(
  owner: string,
  repo: string,
  ref: string,
  maxFiles = MAX_FILES
): Promise<Array<{ path: string; size?: number }>> {
  const out: Array<{ path: string; size?: number }> = [];
  const queue: string[] = [""];
  while (queue.length && out.length < maxFiles) {
    const dir = queue.shift()!;
    let entries: GitTreeEntry[] = [];
    try {
      entries = await getTree(owner, repo, ref, dir);
    } catch {
      continue;
    }
    for (const e of entries) {
      const p = dir ? `${dir}/${e.name}` : e.name;
      if (e.type === "tree") {
        const base = e.name.toLowerCase();
        if (
          base === "node_modules" ||
          base === ".git" ||
          base === "dist" ||
          base === "build" ||
          base === "vendor" ||
          base === ".next" ||
          base === ".turbo" ||
          base === "target" ||
          base === "__pycache__"
        ) {
          continue;
        }
        queue.push(p);
      } else if (e.type === "blob") {
        if (!detectLanguage(p)) continue;
        if (e.size !== undefined && e.size > INDEXABLE_MAX_BYTES) continue;
        out.push({ path: p, size: e.size });
        if (out.length >= maxFiles) break;
      }
    }
  }
  return out;
}

/** Walks the repo tree at HEAD, extracts symbols, replaces the prior set. */
export async function indexRepositorySymbols(
  repositoryId: string
): Promise<{ indexed: number; files: number; commitSha: string } | null> {
  try {
    const [repo] = await db
      .select()
      .from(repositories)
      .where(eq(repositories.id, repositoryId))
      .limit(1);
    if (!repo) return null;

    const [owner] = await db
      .select({ username: users.username })
      .from(users)
      .where(eq(users.id, repo.ownerId))
      .limit(1);
    if (!owner) return null;

    const defaultBranch =
      (await getDefaultBranch(owner.username, repo.name)) || "main";
    const head = await resolveRef(owner.username, repo.name, defaultBranch);
    if (!head) return null;

    const files = await walkCodePaths(owner.username, repo.name, head);

    const rows: Array<Omit<CodeSymbol, "id" | "createdAt">> = [];
    let processed = 0;

    for (const f of files) {
      const lang = detectLanguage(f.path);
      if (!lang) continue;
      try {
        const blob = await getBlob(owner.username, repo.name, head, f.path);
        if (!blob || blob.isBinary) continue;
        const syms = extractSymbols(blob.content, lang);
        for (const s of syms) {
          rows.push({
            repositoryId: repo.id,
            commitSha: head,
            name: s.name,
            kind: s.kind,
            path: f.path,
            line: s.line,
            signature: s.signature,
          });
        }
        processed++;
      } catch {
        // skip unreadable files
      }
    }

    // Replace the prior index (DELETE + batched INSERTs).
    await db.delete(codeSymbols).where(eq(codeSymbols.repositoryId, repo.id));
    const BATCH = 500;
    for (let i = 0; i < rows.length; i += BATCH) {
      await db.insert(codeSymbols).values(rows.slice(i, i + BATCH));
    }

    return { indexed: rows.length, files: processed, commitSha: head };
  } catch (err) {
    console.error("[symbols] indexRepositorySymbols error:", err);
    return null;
  }
}

/** Find definitions of a symbol name within a repo. */
export async function findDefinitions(
  repositoryId: string,
  name: string
): Promise<CodeSymbol[]> {
  try {
    return await db
      .select()
      .from(codeSymbols)
      .where(
        and(eq(codeSymbols.repositoryId, repositoryId), eq(codeSymbols.name, name))
      );
  } catch {
    return [];
  }
}

/** Count total indexed symbols for a repo (pagination helper). */
export async function countSymbolsForRepo(
  repositoryId: string
): Promise<number> {
  try {
    const rows = await db
      .select({ id: codeSymbols.id })
      .from(codeSymbols)
      .where(eq(codeSymbols.repositoryId, repositoryId));
    return rows.length;
  } catch {
    return 0;
  }
}

// Test-only hook
export const __internal = { RULES, EXT_LANG };