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.tsBlame484 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 */
976d7f7Claude116// One-shot warning latch — operators only need to be told once that
117// GateTest is misconfigured. Reset between tests via the export below.
118let _gatetestAuthWarned = false;
119export function _resetGateTestAuthWarning(): void {
120 _gatetestAuthWarned = false;
121}
122
170ddb2Claude123export async function notifyGateTestOfPush(
124 owner: string,
125 repo: string,
126 ref: string,
127 headSha: string
128): Promise<void> {
129 if (!process.env.GATETEST_URL) return;
130 try {
131 const headers: Record<string, string> = {
132 "Content-Type": "application/json",
133 };
134 if (config.gatetestApiKey) {
135 headers["Authorization"] = `Bearer ${config.gatetestApiKey}`;
976d7f7Claude136 } else if (!_gatetestAuthWarned) {
137 // GATETEST_URL is set but GATETEST_API_KEY is missing. GateTest
138 // rejects unauthenticated requests with 401 — the scan never
139 // actually runs but the push looks like it fired. Warn once so
140 // operators notice (silent-fail audit, item §4 in AUDIT-v2.md).
141 _gatetestAuthWarned = true;
142 console.warn(
143 "[gatetest] GATETEST_URL is set but GATETEST_API_KEY is empty — push notifications will be rejected by GateTest with 401. Set GATETEST_API_KEY in the deploy environment to enable scans."
144 );
170ddb2Claude145 }
146 const res = await fetch(config.gatetestUrl, {
147 method: "POST",
148 headers,
149 body: JSON.stringify({
150 repository: `${owner}/${repo}`,
151 ref,
152 sha: headSha,
153 source: "gluecron",
154 mode: "async",
155 }),
156 signal: AbortSignal.timeout(10_000),
157 });
158 if (!res.ok) {
159 const body = await res.text().catch(() => "");
160 console.warn(
161 `[gatetest] push notify returned ${res.status} for ${owner}/${repo}@${headSha.slice(0, 7)}: ${body.slice(0, 200)}`
162 );
163 }
164 } catch (err) {
165 console.warn(
166 `[gatetest] push notify failed for ${owner}/${repo}@${headSha.slice(0, 7)}:`,
167 err instanceof Error ? err.message : err
168 );
169 }
170}
171
e883329Claude172/**
173 * Run GateTest scan on a repository at a specific ref.
174 */
175export async function runGateTestScan(
176 owner: string,
177 repo: string,
178 ref: string,
179 headSha: string
180): Promise<GateCheckResult> {
181 if (!config.gatetestUrl) {
3ef4c9dClaude182 return { name: "GateTest", passed: true, details: "GateTest URL not configured — skipped", skipped: true };
e883329Claude183 }
184
185 try {
3ef4c9dClaude186 const headers: Record<string, string> = { "Content-Type": "application/json" };
e883329Claude187 if (config.gatetestApiKey) {
188 headers["Authorization"] = `Bearer ${config.gatetestApiKey}`;
189 }
190
191 const response = await fetch(config.gatetestUrl, {
192 method: "POST",
193 headers,
194 body: JSON.stringify({
195 repository: `${owner}/${repo}`,
196 ref,
197 sha: headSha,
198 source: "gluecron",
3ef4c9dClaude199 mode: "blocking",
e883329Claude200 }),
3ef4c9dClaude201 signal: AbortSignal.timeout(60_000),
e883329Claude202 });
203
204 if (!response.ok) {
205 const body = await response.text().catch(() => "");
206 return {
207 name: "GateTest",
208 passed: false,
209 details: `GateTest returned ${response.status}: ${body.slice(0, 200)}`,
210 };
211 }
212
3ef4c9dClaude213 const result = (await response.json().catch(() => ({}))) as Record<string, unknown>;
214 const passed =
215 result.passed === true || result.status === "passed" || result.status === "success";
216 const summary =
217 (result.summary as string) || (result.message as string) || (passed ? "All checks passed" : "Checks failed");
218 return { name: "GateTest", passed, details: summary };
e883329Claude219 } catch (err) {
220 console.error("[gate] GateTest scan error:", err);
221 return {
222 name: "GateTest",
223 passed: false,
224 details: `GateTest scan failed: ${err instanceof Error ? err.message : "Unknown error"}`,
225 };
226 }
227}
228
229/**
230 * Check for merge conflicts between branches.
231 */
232export async function checkMergeability(
233 owner: string,
234 repo: string,
235 baseBranch: string,
236 headBranch: string
237): Promise<GateCheckResult> {
238 const { getRepoPath } = await import("../git/repository");
239 const repoDir = getRepoPath(owner, repo);
240
241 const ffCheck = Bun.spawn(
242 ["git", "merge-base", "--is-ancestor", baseBranch, headBranch],
243 { cwd: repoDir, stdout: "pipe", stderr: "pipe" }
244 );
245 const ffExit = await ffCheck.exited;
246 if (ffExit === 0) {
247 return { name: "Merge check", passed: true, details: "Fast-forward merge possible" };
248 }
249
250 const mergeBase = Bun.spawn(
251 ["git", "merge-base", baseBranch, headBranch],
252 { cwd: repoDir, stdout: "pipe", stderr: "pipe" }
253 );
254 const baseOut = await new Response(mergeBase.stdout).text();
255 const baseExit = await mergeBase.exited;
256
257 if (baseExit !== 0) {
258 return { name: "Merge check", passed: false, details: "Branches have no common ancestor" };
259 }
260
261 const mergeTree = Bun.spawn(
262 ["git", "merge-tree", baseOut.trim(), baseBranch, headBranch],
263 { cwd: repoDir, stdout: "pipe", stderr: "pipe" }
264 );
265 const treeOut = await new Response(mergeTree.stdout).text();
266 await mergeTree.exited;
267
268 const hasConflicts = treeOut.includes("<<<<<<<");
269 return {
270 name: "Merge check",
271 passed: !hasConflicts,
272 details: hasConflicts
273 ? "Merge conflicts detected — auto-resolution will be attempted"
274 : "Clean merge possible",
275 };
276}
277
278/**
3ef4c9dClaude279 * Secret + security scan. Runs the regex scanner on files at the given ref,
280 * then optionally runs the AI semantic scan on the diff.
281 */
282export async function runSecretAndSecurityScan(
283 owner: string,
284 repo: string,
285 ref: string,
286 headSha: string,
287 opts: { scanSecrets: boolean; scanSecurity: boolean; diffText?: string }
288): Promise<{
289 secretResult: GateCheckResult;
290 securityResult: GateCheckResult;
291 secrets: SecretFinding[];
292 securityIssues: SecurityFinding[];
293}> {
294 const { getRepoPath, getTree, getBlob, listBranches } = await import("../git/repository");
295 const repoDir = getRepoPath(owner, repo);
296
297 // Snapshot top-level + one level deep files at the ref
298 const files: Array<{ path: string; content: string }> = [];
299 const branches = await listBranches(owner, repo);
300 const effectiveRef = branches.includes(ref.replace(/^refs\/heads\//, ""))
301 ? ref.replace(/^refs\/heads\//, "")
302 : headSha;
303
304 async function walk(dir: string, depth: number): Promise<void> {
305 if (depth > 4) return;
306 const tree = await getTree(owner, repo, effectiveRef, dir);
307 for (const entry of tree) {
308 const full = dir ? `${dir}/${entry.name}` : entry.name;
309 if (entry.type === "tree") {
310 await walk(full, depth + 1);
311 } else if (entry.type === "blob" && (entry.size ?? 0) < 200_000) {
312 try {
313 const blob = await getBlob(owner, repo, effectiveRef, full);
314 if (blob && !blob.isBinary) {
315 files.push({ path: full, content: blob.content });
316 }
317 } catch {
318 // skip
319 }
320 }
321 if (files.length >= 500) return;
322 }
323 }
324
325 try {
326 await walk("", 0);
327 } catch {
328 // Unable to walk — the ref may not exist yet. Bail gracefully.
329 }
330
331 const secrets = opts.scanSecrets ? scanForSecrets(files) : [];
332 const securityIssues =
333 opts.scanSecurity && opts.diffText ? await aiSecurityScan(`${owner}/${repo}`, opts.diffText) : [];
334
335 const criticalSecrets = secrets.filter((s) => s.severity === "critical").length;
336 const criticalSec = securityIssues.filter((i) => i.severity === "critical" || i.severity === "high").length;
337
338 return {
339 secretResult: {
340 name: "Secret scan",
341 passed: criticalSecrets === 0,
342 details:
343 secrets.length === 0
344 ? "No secrets detected"
345 : `Found ${secrets.length} secret${secrets.length === 1 ? "" : "s"} (${criticalSecrets} critical)`,
346 },
347 securityResult: {
348 name: "Security scan",
349 passed: criticalSec === 0,
350 skipped: !opts.scanSecurity || !opts.diffText,
351 details:
352 securityIssues.length === 0
353 ? opts.scanSecurity && opts.diffText
354 ? "No security issues found"
355 : "Skipped — no diff provided"
356 : `Found ${securityIssues.length} issue${securityIssues.length === 1 ? "" : "s"} (${criticalSec} high/critical)`,
357 },
358 secrets,
359 securityIssues,
360 };
361}
362
363/**
364 * Run every configured gate for a PR merge.
365 * Records gate_runs entries. Optionally invokes auto-repair.
e883329Claude366 */
367export async function runAllGateChecks(
368 owner: string,
369 repo: string,
370 baseBranch: string,
371 headBranch: string,
372 headSha: string,
3ef4c9dClaude373 aiReviewApproved: boolean,
374 opts: {
375 pullRequestId?: string;
376 enableAutoRepair?: boolean;
377 diffText?: string;
378 } = {}
e883329Claude379): Promise<GateResult> {
3ef4c9dClaude380 const started = Date.now();
381 const repoRow = await lookupRepo(owner, repo);
382 const settings = repoRow ? await getOrCreateSettings(repoRow.id) : null;
383
384 // Decide which gates to run
385 const runGateTest = settings?.gateTestEnabled !== false && !!config.gatetestUrl;
386 const runSecretScan = settings?.secretScanEnabled !== false;
387 const runSecurityScan = settings?.securityScanEnabled !== false;
388 const runAiReview = settings?.aiReviewEnabled !== false;
389 const enableRepair = opts.enableAutoRepair !== false && settings?.autoFixEnabled !== false;
e883329Claude390
3ef4c9dClaude391 const [gateTestResult, mergeResult, scanResults] = await Promise.all([
392 runGateTest
393 ? runGateTestScan(owner, repo, `refs/heads/${headBranch}`, headSha)
394 : Promise.resolve<GateCheckResult>({
395 name: "GateTest",
396 passed: true,
397 skipped: true,
398 details: "Disabled in settings",
399 }),
e883329Claude400 checkMergeability(owner, repo, baseBranch, headBranch),
3ef4c9dClaude401 runSecretAndSecurityScan(owner, repo, `refs/heads/${headBranch}`, headSha, {
402 scanSecrets: runSecretScan,
403 scanSecurity: runSecurityScan,
404 diffText: opts.diffText,
405 }),
e883329Claude406 ]);
407
3ef4c9dClaude408 const checks: GateCheckResult[] = [gateTestResult];
409 checks.push(scanResults.secretResult);
410 if (runSecurityScan) checks.push(scanResults.securityResult);
e883329Claude411 checks.push(mergeResult);
412 checks.push({
413 name: "AI Review",
3ef4c9dClaude414 passed: !runAiReview || aiReviewApproved,
415 skipped: !runAiReview,
416 details: !runAiReview
417 ? "Disabled in settings"
418 : aiReviewApproved
419 ? "AI review approved"
420 : "AI review found blocking issues — resolve before merging",
e883329Claude421 });
422
3ef4c9dClaude423 // ---- Auto-repair on failures ----
424 if (enableRepair) {
425 // Secrets
426 if (!scanResults.secretResult.passed) {
427 const repair = await repairSecrets(owner, repo, headBranch, scanResults.secrets);
428 if (repair.success) {
429 scanResults.secretResult.passed = true;
430 scanResults.secretResult.repaired = true;
431 scanResults.secretResult.repairCommitSha = repair.commitSha;
432 scanResults.secretResult.details = `Auto-redacted ${scanResults.secrets.length} secret${scanResults.secrets.length === 1 ? "" : "s"} (${repair.commitSha?.slice(0, 7)})`;
433 }
434 }
435 // Security
436 if (!scanResults.securityResult.passed && scanResults.securityIssues.length > 0) {
437 const repair = await repairSecurityIssues(
438 owner,
439 repo,
440 headBranch,
441 scanResults.securityIssues
442 );
443 if (repair.success) {
444 scanResults.securityResult.passed = true;
445 scanResults.securityResult.repaired = true;
446 scanResults.securityResult.repairCommitSha = repair.commitSha;
447 scanResults.securityResult.details = `Auto-repaired ${repair.filesChanged.length} file${repair.filesChanged.length === 1 ? "" : "s"} (${repair.commitSha?.slice(0, 7)})`;
448 }
449 }
450 }
451
452 // Persist gate_runs
453 if (repoRow) {
454 const duration = Date.now() - started;
455 await Promise.all(
456 checks.map((check) =>
457 recordGateRun({
458 repositoryId: repoRow.id,
459 pullRequestId: opts.pullRequestId,
460 commitSha: headSha,
461 ref: `refs/heads/${headBranch}`,
462 gateName: check.name,
463 status: check.skipped
464 ? "skipped"
465 : check.repaired
466 ? "repaired"
467 : check.passed
468 ? "passed"
469 : "failed",
470 summary: check.details,
471 repairAttempted: !!check.repaired,
472 repairSucceeded: !!check.repaired,
473 repairCommitSha: check.repairCommitSha,
474 durationMs: duration,
475 })
476 )
477 );
478 }
479
e883329Claude480 return {
3ef4c9dClaude481 allPassed: checks.every((c) => c.passed || c.skipped),
e883329Claude482 checks,
483 };
484}