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.tsBlame492 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
6f1fd83Claude241 function spawnGit(args: string[]) {
242 try {
243 return Bun.spawn(["git", ...args], { cwd: repoDir, stdout: "pipe", stderr: "pipe" });
244 } catch {
245 return null;
246 }
247 }
248
249 const ffCheck = spawnGit(["merge-base", "--is-ancestor", baseBranch, headBranch]);
250 if (!ffCheck) {
251 return { name: "Merge check", passed: false, skipped: true, details: "Repository not accessible" };
252 }
e883329Claude253 const ffExit = await ffCheck.exited;
254 if (ffExit === 0) {
255 return { name: "Merge check", passed: true, details: "Fast-forward merge possible" };
256 }
257
6f1fd83Claude258 const mergeBase = spawnGit(["merge-base", baseBranch, headBranch]);
259 if (!mergeBase) {
260 return { name: "Merge check", passed: false, details: "Branches have no common ancestor" };
261 }
e883329Claude262 const baseOut = await new Response(mergeBase.stdout).text();
263 const baseExit = await mergeBase.exited;
264
265 if (baseExit !== 0) {
266 return { name: "Merge check", passed: false, details: "Branches have no common ancestor" };
267 }
268
6f1fd83Claude269 const mergeTree = spawnGit(["merge-tree", baseOut.trim(), baseBranch, headBranch]);
270 if (!mergeTree) {
271 return { name: "Merge check", passed: false, details: "Branches have no common ancestor" };
272 }
e883329Claude273 const treeOut = await new Response(mergeTree.stdout).text();
274 await mergeTree.exited;
275
276 const hasConflicts = treeOut.includes("<<<<<<<");
277 return {
278 name: "Merge check",
279 passed: !hasConflicts,
280 details: hasConflicts
281 ? "Merge conflicts detected — auto-resolution will be attempted"
282 : "Clean merge possible",
283 };
284}
285
286/**
3ef4c9dClaude287 * Secret + security scan. Runs the regex scanner on files at the given ref,
288 * then optionally runs the AI semantic scan on the diff.
289 */
290export async function runSecretAndSecurityScan(
291 owner: string,
292 repo: string,
293 ref: string,
294 headSha: string,
295 opts: { scanSecrets: boolean; scanSecurity: boolean; diffText?: string }
296): Promise<{
297 secretResult: GateCheckResult;
298 securityResult: GateCheckResult;
299 secrets: SecretFinding[];
300 securityIssues: SecurityFinding[];
301}> {
302 const { getRepoPath, getTree, getBlob, listBranches } = await import("../git/repository");
303 const repoDir = getRepoPath(owner, repo);
304
305 // Snapshot top-level + one level deep files at the ref
306 const files: Array<{ path: string; content: string }> = [];
307 const branches = await listBranches(owner, repo);
308 const effectiveRef = branches.includes(ref.replace(/^refs\/heads\//, ""))
309 ? ref.replace(/^refs\/heads\//, "")
310 : headSha;
311
312 async function walk(dir: string, depth: number): Promise<void> {
313 if (depth > 4) return;
314 const tree = await getTree(owner, repo, effectiveRef, dir);
315 for (const entry of tree) {
316 const full = dir ? `${dir}/${entry.name}` : entry.name;
317 if (entry.type === "tree") {
318 await walk(full, depth + 1);
319 } else if (entry.type === "blob" && (entry.size ?? 0) < 200_000) {
320 try {
321 const blob = await getBlob(owner, repo, effectiveRef, full);
322 if (blob && !blob.isBinary) {
323 files.push({ path: full, content: blob.content });
324 }
325 } catch {
326 // skip
327 }
328 }
329 if (files.length >= 500) return;
330 }
331 }
332
333 try {
334 await walk("", 0);
335 } catch {
336 // Unable to walk — the ref may not exist yet. Bail gracefully.
337 }
338
339 const secrets = opts.scanSecrets ? scanForSecrets(files) : [];
340 const securityIssues =
341 opts.scanSecurity && opts.diffText ? await aiSecurityScan(`${owner}/${repo}`, opts.diffText) : [];
342
343 const criticalSecrets = secrets.filter((s) => s.severity === "critical").length;
344 const criticalSec = securityIssues.filter((i) => i.severity === "critical" || i.severity === "high").length;
345
346 return {
347 secretResult: {
348 name: "Secret scan",
349 passed: criticalSecrets === 0,
350 details:
351 secrets.length === 0
352 ? "No secrets detected"
353 : `Found ${secrets.length} secret${secrets.length === 1 ? "" : "s"} (${criticalSecrets} critical)`,
354 },
355 securityResult: {
356 name: "Security scan",
357 passed: criticalSec === 0,
358 skipped: !opts.scanSecurity || !opts.diffText,
359 details:
360 securityIssues.length === 0
361 ? opts.scanSecurity && opts.diffText
362 ? "No security issues found"
363 : "Skipped — no diff provided"
364 : `Found ${securityIssues.length} issue${securityIssues.length === 1 ? "" : "s"} (${criticalSec} high/critical)`,
365 },
366 secrets,
367 securityIssues,
368 };
369}
370
371/**
372 * Run every configured gate for a PR merge.
373 * Records gate_runs entries. Optionally invokes auto-repair.
e883329Claude374 */
375export async function runAllGateChecks(
376 owner: string,
377 repo: string,
378 baseBranch: string,
379 headBranch: string,
380 headSha: string,
3ef4c9dClaude381 aiReviewApproved: boolean,
382 opts: {
383 pullRequestId?: string;
384 enableAutoRepair?: boolean;
385 diffText?: string;
386 } = {}
e883329Claude387): Promise<GateResult> {
3ef4c9dClaude388 const started = Date.now();
389 const repoRow = await lookupRepo(owner, repo);
390 const settings = repoRow ? await getOrCreateSettings(repoRow.id) : null;
391
392 // Decide which gates to run
393 const runGateTest = settings?.gateTestEnabled !== false && !!config.gatetestUrl;
394 const runSecretScan = settings?.secretScanEnabled !== false;
395 const runSecurityScan = settings?.securityScanEnabled !== false;
396 const runAiReview = settings?.aiReviewEnabled !== false;
397 const enableRepair = opts.enableAutoRepair !== false && settings?.autoFixEnabled !== false;
e883329Claude398
3ef4c9dClaude399 const [gateTestResult, mergeResult, scanResults] = await Promise.all([
400 runGateTest
401 ? runGateTestScan(owner, repo, `refs/heads/${headBranch}`, headSha)
402 : Promise.resolve<GateCheckResult>({
403 name: "GateTest",
404 passed: true,
405 skipped: true,
406 details: "Disabled in settings",
407 }),
e883329Claude408 checkMergeability(owner, repo, baseBranch, headBranch),
3ef4c9dClaude409 runSecretAndSecurityScan(owner, repo, `refs/heads/${headBranch}`, headSha, {
410 scanSecrets: runSecretScan,
411 scanSecurity: runSecurityScan,
412 diffText: opts.diffText,
413 }),
e883329Claude414 ]);
415
3ef4c9dClaude416 const checks: GateCheckResult[] = [gateTestResult];
417 checks.push(scanResults.secretResult);
418 if (runSecurityScan) checks.push(scanResults.securityResult);
e883329Claude419 checks.push(mergeResult);
420 checks.push({
421 name: "AI Review",
3ef4c9dClaude422 passed: !runAiReview || aiReviewApproved,
423 skipped: !runAiReview,
424 details: !runAiReview
425 ? "Disabled in settings"
426 : aiReviewApproved
427 ? "AI review approved"
428 : "AI review found blocking issues — resolve before merging",
e883329Claude429 });
430
3ef4c9dClaude431 // ---- Auto-repair on failures ----
432 if (enableRepair) {
433 // Secrets
434 if (!scanResults.secretResult.passed) {
435 const repair = await repairSecrets(owner, repo, headBranch, scanResults.secrets);
436 if (repair.success) {
437 scanResults.secretResult.passed = true;
438 scanResults.secretResult.repaired = true;
439 scanResults.secretResult.repairCommitSha = repair.commitSha;
440 scanResults.secretResult.details = `Auto-redacted ${scanResults.secrets.length} secret${scanResults.secrets.length === 1 ? "" : "s"} (${repair.commitSha?.slice(0, 7)})`;
441 }
442 }
443 // Security
444 if (!scanResults.securityResult.passed && scanResults.securityIssues.length > 0) {
445 const repair = await repairSecurityIssues(
446 owner,
447 repo,
448 headBranch,
449 scanResults.securityIssues
450 );
451 if (repair.success) {
452 scanResults.securityResult.passed = true;
453 scanResults.securityResult.repaired = true;
454 scanResults.securityResult.repairCommitSha = repair.commitSha;
455 scanResults.securityResult.details = `Auto-repaired ${repair.filesChanged.length} file${repair.filesChanged.length === 1 ? "" : "s"} (${repair.commitSha?.slice(0, 7)})`;
456 }
457 }
458 }
459
460 // Persist gate_runs
461 if (repoRow) {
462 const duration = Date.now() - started;
463 await Promise.all(
464 checks.map((check) =>
465 recordGateRun({
466 repositoryId: repoRow.id,
467 pullRequestId: opts.pullRequestId,
468 commitSha: headSha,
469 ref: `refs/heads/${headBranch}`,
470 gateName: check.name,
471 status: check.skipped
472 ? "skipped"
473 : check.repaired
474 ? "repaired"
475 : check.passed
476 ? "passed"
477 : "failed",
478 summary: check.details,
479 repairAttempted: !!check.repaired,
480 repairSucceeded: !!check.repaired,
481 repairCommitSha: check.repairCommitSha,
482 durationMs: duration,
483 })
484 )
485 );
486 }
487
e883329Claude488 return {
3ef4c9dClaude489 allPassed: checks.every((c) => c.passed || c.skipped),
e883329Claude490 checks,
491 };
492}