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
Blame · Line-by-line history

gate.ts

Each line is annotated with the commit that last touched it. Click any SHA to jump to that commit and see the surrounding change.

gate.tsBlame468 lines · 1 contributor
e883329Claude1/**
3ef4c9dClaude2 * Green gate enforcement — the heart of the "nothing broken ships" guarantee.
e883329Claude3 *
3ef4c9dClaude4 * Runs every configured gate for a repo on push / on PR / on merge:
5 * 1. GateTest scan (external test/lint runner)
6 * 2. Secret scan (regex secrets + AI security review)
7 * 3. AI code review (for PRs)
8 * 4. Merge check (for PRs)
9 * 5. Dependency/vuln scan (best-effort, skipped if not configured)
e883329Claude10 *
3ef4c9dClaude11 * Each result is persisted to `gate_runs`. If auto-repair is enabled
12 * and a gate fails, the engine attempts a fix before reporting a hard fail.
e883329Claude13 */
14
3ef4c9dClaude15import { eq } from "drizzle-orm";
e883329Claude16import { config } from "./config";
3ef4c9dClaude17import { db } from "../db";
18import { gateRuns, repoSettings, repositories, users } from "../db/schema";
19import { getOrCreateSettings } from "./repo-bootstrap";
20import { scanForSecrets, aiSecurityScan } from "./security-scan";
21import type { SecretFinding, SecurityFinding } from "./security-scan";
22import { repairSecrets, repairSecurityIssues } from "./auto-repair";
23import { readFile } from "fs/promises";
24import { join } from "path";
e883329Claude25
26export interface GateCheckResult {
27 name: string;
28 passed: boolean;
29 details: string;
3ef4c9dClaude30 skipped?: boolean;
31 repaired?: boolean;
32 repairCommitSha?: string;
e883329Claude33}
34
35export interface GateResult {
36 allPassed: boolean;
37 checks: GateCheckResult[];
38}
39
3ef4c9dClaude40/**
41 * Record a gate run in the DB. Fire-and-forget; swallows DB errors.
42 */
43async function recordGateRun(opts: {
44 repositoryId: string;
45 pullRequestId?: string;
46 commitSha: string;
47 ref: string;
48 gateName: string;
49 status: "passed" | "failed" | "skipped" | "repaired";
50 summary: string;
51 details?: unknown;
52 repairAttempted?: boolean;
53 repairSucceeded?: boolean;
54 repairCommitSha?: string;
55 durationMs?: number;
56}): Promise<void> {
57 try {
58 await db.insert(gateRuns).values({
59 repositoryId: opts.repositoryId,
60 pullRequestId: opts.pullRequestId,
61 commitSha: opts.commitSha,
62 ref: opts.ref,
63 gateName: opts.gateName,
64 status: opts.status,
65 summary: opts.summary,
66 details: opts.details ? JSON.stringify(opts.details) : null,
67 repairAttempted: opts.repairAttempted ?? false,
68 repairSucceeded: opts.repairSucceeded ?? false,
69 repairCommitSha: opts.repairCommitSha,
70 durationMs: opts.durationMs,
71 completedAt: new Date(),
72 });
73 } catch (err) {
74 console.error("[gate] recordGateRun failed:", err);
75 }
76}
77
78/**
79 * Look up the repository row by owner/name.
80 */
81async function lookupRepo(
82 owner: string,
83 repo: string
84): Promise<{ id: string } | null> {
85 try {
86 const [u] = await db.select().from(users).where(eq(users.username, owner)).limit(1);
87 if (!u) return null;
88 const { and } = await import("drizzle-orm");
89 const [r] = await db
90 .select()
91 .from(repositories)
92 .where(and(eq(repositories.ownerId, u.id), eq(repositories.name, repo)))
93 .limit(1);
94 return r ? { id: r.id } : null;
95 } catch {
96 return null;
97 }
98}
99
170ddb2Claude100/**
101 * Fire-and-forget post-receive notification to GateTest.
102 *
103 * Called from `src/hooks/post-receive.ts` for every push when
104 * `GATETEST_URL` is set. Unlike `runGateTestScan` (which is used by the
105 * PR merge gate and AWAITS a blocking result), this helper just notifies
106 * GateTest that a push happened and lets GateTest POST results back via
107 * the existing inbound webhook at `/api/hooks/gatetest`. Never throws,
108 * never blocks the push. 10-second timeout so a slow GateTest endpoint
109 * can't hang the post-receive hook chain.
110 *
111 * Was a stub before 2026-05-16; `src/hooks/post-receive.ts:80` had the
112 * comment "triggerGateTest helper is slated for the intelligence
113 * rework" but nothing called it. CLAUDE.md claims "git push POSTs to
114 * it" — this restores that contract.
115 */
116export async function notifyGateTestOfPush(
117 owner: string,
118 repo: string,
119 ref: string,
120 headSha: string
121): Promise<void> {
122 if (!process.env.GATETEST_URL) return;
123 try {
124 const headers: Record<string, string> = {
125 "Content-Type": "application/json",
126 };
127 if (config.gatetestApiKey) {
128 headers["Authorization"] = `Bearer ${config.gatetestApiKey}`;
129 }
130 const res = await fetch(config.gatetestUrl, {
131 method: "POST",
132 headers,
133 body: JSON.stringify({
134 repository: `${owner}/${repo}`,
135 ref,
136 sha: headSha,
137 source: "gluecron",
138 mode: "async",
139 }),
140 signal: AbortSignal.timeout(10_000),
141 });
142 if (!res.ok) {
143 const body = await res.text().catch(() => "");
144 console.warn(
145 `[gatetest] push notify returned ${res.status} for ${owner}/${repo}@${headSha.slice(0, 7)}: ${body.slice(0, 200)}`
146 );
147 }
148 } catch (err) {
149 console.warn(
150 `[gatetest] push notify failed for ${owner}/${repo}@${headSha.slice(0, 7)}:`,
151 err instanceof Error ? err.message : err
152 );
153 }
154}
155
e883329Claude156/**
157 * Run GateTest scan on a repository at a specific ref.
158 */
159export async function runGateTestScan(
160 owner: string,
161 repo: string,
162 ref: string,
163 headSha: string
164): Promise<GateCheckResult> {
165 if (!config.gatetestUrl) {
3ef4c9dClaude166 return { name: "GateTest", passed: true, details: "GateTest URL not configured — skipped", skipped: true };
e883329Claude167 }
168
169 try {
3ef4c9dClaude170 const headers: Record<string, string> = { "Content-Type": "application/json" };
e883329Claude171 if (config.gatetestApiKey) {
172 headers["Authorization"] = `Bearer ${config.gatetestApiKey}`;
173 }
174
175 const response = await fetch(config.gatetestUrl, {
176 method: "POST",
177 headers,
178 body: JSON.stringify({
179 repository: `${owner}/${repo}`,
180 ref,
181 sha: headSha,
182 source: "gluecron",
3ef4c9dClaude183 mode: "blocking",
e883329Claude184 }),
3ef4c9dClaude185 signal: AbortSignal.timeout(60_000),
e883329Claude186 });
187
188 if (!response.ok) {
189 const body = await response.text().catch(() => "");
190 return {
191 name: "GateTest",
192 passed: false,
193 details: `GateTest returned ${response.status}: ${body.slice(0, 200)}`,
194 };
195 }
196
3ef4c9dClaude197 const result = (await response.json().catch(() => ({}))) as Record<string, unknown>;
198 const passed =
199 result.passed === true || result.status === "passed" || result.status === "success";
200 const summary =
201 (result.summary as string) || (result.message as string) || (passed ? "All checks passed" : "Checks failed");
202 return { name: "GateTest", passed, details: summary };
e883329Claude203 } catch (err) {
204 console.error("[gate] GateTest scan error:", err);
205 return {
206 name: "GateTest",
207 passed: false,
208 details: `GateTest scan failed: ${err instanceof Error ? err.message : "Unknown error"}`,
209 };
210 }
211}
212
213/**
214 * Check for merge conflicts between branches.
215 */
216export async function checkMergeability(
217 owner: string,
218 repo: string,
219 baseBranch: string,
220 headBranch: string
221): Promise<GateCheckResult> {
222 const { getRepoPath } = await import("../git/repository");
223 const repoDir = getRepoPath(owner, repo);
224
225 const ffCheck = Bun.spawn(
226 ["git", "merge-base", "--is-ancestor", baseBranch, headBranch],
227 { cwd: repoDir, stdout: "pipe", stderr: "pipe" }
228 );
229 const ffExit = await ffCheck.exited;
230 if (ffExit === 0) {
231 return { name: "Merge check", passed: true, details: "Fast-forward merge possible" };
232 }
233
234 const mergeBase = Bun.spawn(
235 ["git", "merge-base", baseBranch, headBranch],
236 { cwd: repoDir, stdout: "pipe", stderr: "pipe" }
237 );
238 const baseOut = await new Response(mergeBase.stdout).text();
239 const baseExit = await mergeBase.exited;
240
241 if (baseExit !== 0) {
242 return { name: "Merge check", passed: false, details: "Branches have no common ancestor" };
243 }
244
245 const mergeTree = Bun.spawn(
246 ["git", "merge-tree", baseOut.trim(), baseBranch, headBranch],
247 { cwd: repoDir, stdout: "pipe", stderr: "pipe" }
248 );
249 const treeOut = await new Response(mergeTree.stdout).text();
250 await mergeTree.exited;
251
252 const hasConflicts = treeOut.includes("<<<<<<<");
253 return {
254 name: "Merge check",
255 passed: !hasConflicts,
256 details: hasConflicts
257 ? "Merge conflicts detected — auto-resolution will be attempted"
258 : "Clean merge possible",
259 };
260}
261
262/**
3ef4c9dClaude263 * Secret + security scan. Runs the regex scanner on files at the given ref,
264 * then optionally runs the AI semantic scan on the diff.
265 */
266export async function runSecretAndSecurityScan(
267 owner: string,
268 repo: string,
269 ref: string,
270 headSha: string,
271 opts: { scanSecrets: boolean; scanSecurity: boolean; diffText?: string }
272): Promise<{
273 secretResult: GateCheckResult;
274 securityResult: GateCheckResult;
275 secrets: SecretFinding[];
276 securityIssues: SecurityFinding[];
277}> {
278 const { getRepoPath, getTree, getBlob, listBranches } = await import("../git/repository");
279 const repoDir = getRepoPath(owner, repo);
280
281 // Snapshot top-level + one level deep files at the ref
282 const files: Array<{ path: string; content: string }> = [];
283 const branches = await listBranches(owner, repo);
284 const effectiveRef = branches.includes(ref.replace(/^refs\/heads\//, ""))
285 ? ref.replace(/^refs\/heads\//, "")
286 : headSha;
287
288 async function walk(dir: string, depth: number): Promise<void> {
289 if (depth > 4) return;
290 const tree = await getTree(owner, repo, effectiveRef, dir);
291 for (const entry of tree) {
292 const full = dir ? `${dir}/${entry.name}` : entry.name;
293 if (entry.type === "tree") {
294 await walk(full, depth + 1);
295 } else if (entry.type === "blob" && (entry.size ?? 0) < 200_000) {
296 try {
297 const blob = await getBlob(owner, repo, effectiveRef, full);
298 if (blob && !blob.isBinary) {
299 files.push({ path: full, content: blob.content });
300 }
301 } catch {
302 // skip
303 }
304 }
305 if (files.length >= 500) return;
306 }
307 }
308
309 try {
310 await walk("", 0);
311 } catch {
312 // Unable to walk — the ref may not exist yet. Bail gracefully.
313 }
314
315 const secrets = opts.scanSecrets ? scanForSecrets(files) : [];
316 const securityIssues =
317 opts.scanSecurity && opts.diffText ? await aiSecurityScan(`${owner}/${repo}`, opts.diffText) : [];
318
319 const criticalSecrets = secrets.filter((s) => s.severity === "critical").length;
320 const criticalSec = securityIssues.filter((i) => i.severity === "critical" || i.severity === "high").length;
321
322 return {
323 secretResult: {
324 name: "Secret scan",
325 passed: criticalSecrets === 0,
326 details:
327 secrets.length === 0
328 ? "No secrets detected"
329 : `Found ${secrets.length} secret${secrets.length === 1 ? "" : "s"} (${criticalSecrets} critical)`,
330 },
331 securityResult: {
332 name: "Security scan",
333 passed: criticalSec === 0,
334 skipped: !opts.scanSecurity || !opts.diffText,
335 details:
336 securityIssues.length === 0
337 ? opts.scanSecurity && opts.diffText
338 ? "No security issues found"
339 : "Skipped — no diff provided"
340 : `Found ${securityIssues.length} issue${securityIssues.length === 1 ? "" : "s"} (${criticalSec} high/critical)`,
341 },
342 secrets,
343 securityIssues,
344 };
345}
346
347/**
348 * Run every configured gate for a PR merge.
349 * Records gate_runs entries. Optionally invokes auto-repair.
e883329Claude350 */
351export async function runAllGateChecks(
352 owner: string,
353 repo: string,
354 baseBranch: string,
355 headBranch: string,
356 headSha: string,
3ef4c9dClaude357 aiReviewApproved: boolean,
358 opts: {
359 pullRequestId?: string;
360 enableAutoRepair?: boolean;
361 diffText?: string;
362 } = {}
e883329Claude363): Promise<GateResult> {
3ef4c9dClaude364 const started = Date.now();
365 const repoRow = await lookupRepo(owner, repo);
366 const settings = repoRow ? await getOrCreateSettings(repoRow.id) : null;
367
368 // Decide which gates to run
369 const runGateTest = settings?.gateTestEnabled !== false && !!config.gatetestUrl;
370 const runSecretScan = settings?.secretScanEnabled !== false;
371 const runSecurityScan = settings?.securityScanEnabled !== false;
372 const runAiReview = settings?.aiReviewEnabled !== false;
373 const enableRepair = opts.enableAutoRepair !== false && settings?.autoFixEnabled !== false;
e883329Claude374
3ef4c9dClaude375 const [gateTestResult, mergeResult, scanResults] = await Promise.all([
376 runGateTest
377 ? runGateTestScan(owner, repo, `refs/heads/${headBranch}`, headSha)
378 : Promise.resolve<GateCheckResult>({
379 name: "GateTest",
380 passed: true,
381 skipped: true,
382 details: "Disabled in settings",
383 }),
e883329Claude384 checkMergeability(owner, repo, baseBranch, headBranch),
3ef4c9dClaude385 runSecretAndSecurityScan(owner, repo, `refs/heads/${headBranch}`, headSha, {
386 scanSecrets: runSecretScan,
387 scanSecurity: runSecurityScan,
388 diffText: opts.diffText,
389 }),
e883329Claude390 ]);
391
3ef4c9dClaude392 const checks: GateCheckResult[] = [gateTestResult];
393 checks.push(scanResults.secretResult);
394 if (runSecurityScan) checks.push(scanResults.securityResult);
e883329Claude395 checks.push(mergeResult);
396 checks.push({
397 name: "AI Review",
3ef4c9dClaude398 passed: !runAiReview || aiReviewApproved,
399 skipped: !runAiReview,
400 details: !runAiReview
401 ? "Disabled in settings"
402 : aiReviewApproved
403 ? "AI review approved"
404 : "AI review found blocking issues — resolve before merging",
e883329Claude405 });
406
3ef4c9dClaude407 // ---- Auto-repair on failures ----
408 if (enableRepair) {
409 // Secrets
410 if (!scanResults.secretResult.passed) {
411 const repair = await repairSecrets(owner, repo, headBranch, scanResults.secrets);
412 if (repair.success) {
413 scanResults.secretResult.passed = true;
414 scanResults.secretResult.repaired = true;
415 scanResults.secretResult.repairCommitSha = repair.commitSha;
416 scanResults.secretResult.details = `Auto-redacted ${scanResults.secrets.length} secret${scanResults.secrets.length === 1 ? "" : "s"} (${repair.commitSha?.slice(0, 7)})`;
417 }
418 }
419 // Security
420 if (!scanResults.securityResult.passed && scanResults.securityIssues.length > 0) {
421 const repair = await repairSecurityIssues(
422 owner,
423 repo,
424 headBranch,
425 scanResults.securityIssues
426 );
427 if (repair.success) {
428 scanResults.securityResult.passed = true;
429 scanResults.securityResult.repaired = true;
430 scanResults.securityResult.repairCommitSha = repair.commitSha;
431 scanResults.securityResult.details = `Auto-repaired ${repair.filesChanged.length} file${repair.filesChanged.length === 1 ? "" : "s"} (${repair.commitSha?.slice(0, 7)})`;
432 }
433 }
434 }
435
436 // Persist gate_runs
437 if (repoRow) {
438 const duration = Date.now() - started;
439 await Promise.all(
440 checks.map((check) =>
441 recordGateRun({
442 repositoryId: repoRow.id,
443 pullRequestId: opts.pullRequestId,
444 commitSha: headSha,
445 ref: `refs/heads/${headBranch}`,
446 gateName: check.name,
447 status: check.skipped
448 ? "skipped"
449 : check.repaired
450 ? "repaired"
451 : check.passed
452 ? "passed"
453 : "failed",
454 summary: check.details,
455 repairAttempted: !!check.repaired,
456 repairSucceeded: !!check.repaired,
457 repairCommitSha: check.repairCommitSha,
458 durationMs: duration,
459 })
460 )
461 );
462 }
463
e883329Claude464 return {
3ef4c9dClaude465 allPassed: checks.every((c) => c.passed || c.skipped),
e883329Claude466 checks,
467 };
468}