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
gate.ts16.0 KB · 492 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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
/**
 * Green gate enforcement — the heart of the "nothing broken ships" guarantee.
 *
 * Runs every configured gate for a repo on push / on PR / on merge:
 *   1. GateTest scan          (external test/lint runner)
 *   2. Secret scan            (regex secrets + AI security review)
 *   3. AI code review         (for PRs)
 *   4. Merge check            (for PRs)
 *   5. Dependency/vuln scan   (best-effort, skipped if not configured)
 *
 * Each result is persisted to `gate_runs`. If auto-repair is enabled
 * and a gate fails, the engine attempts a fix before reporting a hard fail.
 */

import { eq } from "drizzle-orm";
import { config } from "./config";
import { db } from "../db";
import { gateRuns, repoSettings, repositories, users } from "../db/schema";
import { getOrCreateSettings } from "./repo-bootstrap";
import { scanForSecrets, aiSecurityScan } from "./security-scan";
import type { SecretFinding, SecurityFinding } from "./security-scan";
import { repairSecrets, repairSecurityIssues } from "./auto-repair";
import { readFile } from "fs/promises";
import { join } from "path";

export interface GateCheckResult {
  name: string;
  passed: boolean;
  details: string;
  skipped?: boolean;
  repaired?: boolean;
  repairCommitSha?: string;
}

export interface GateResult {
  allPassed: boolean;
  checks: GateCheckResult[];
}

/**
 * Record a gate run in the DB. Fire-and-forget; swallows DB errors.
 */
async function recordGateRun(opts: {
  repositoryId: string;
  pullRequestId?: string;
  commitSha: string;
  ref: string;
  gateName: string;
  status: "passed" | "failed" | "skipped" | "repaired";
  summary: string;
  details?: unknown;
  repairAttempted?: boolean;
  repairSucceeded?: boolean;
  repairCommitSha?: string;
  durationMs?: number;
}): Promise<void> {
  try {
    await db.insert(gateRuns).values({
      repositoryId: opts.repositoryId,
      pullRequestId: opts.pullRequestId,
      commitSha: opts.commitSha,
      ref: opts.ref,
      gateName: opts.gateName,
      status: opts.status,
      summary: opts.summary,
      details: opts.details ? JSON.stringify(opts.details) : null,
      repairAttempted: opts.repairAttempted ?? false,
      repairSucceeded: opts.repairSucceeded ?? false,
      repairCommitSha: opts.repairCommitSha,
      durationMs: opts.durationMs,
      completedAt: new Date(),
    });
  } catch (err) {
    console.error("[gate] recordGateRun failed:", err);
  }
}

/**
 * Look up the repository row by owner/name.
 */
async function lookupRepo(
  owner: string,
  repo: string
): Promise<{ id: string } | null> {
  try {
    const [u] = await db.select().from(users).where(eq(users.username, owner)).limit(1);
    if (!u) return null;
    const { and } = await import("drizzle-orm");
    const [r] = await db
      .select()
      .from(repositories)
      .where(and(eq(repositories.ownerId, u.id), eq(repositories.name, repo)))
      .limit(1);
    return r ? { id: r.id } : null;
  } catch {
    return null;
  }
}

/**
 * Fire-and-forget post-receive notification to GateTest.
 *
 * Called from `src/hooks/post-receive.ts` for every push when
 * `GATETEST_URL` is set. Unlike `runGateTestScan` (which is used by the
 * PR merge gate and AWAITS a blocking result), this helper just notifies
 * GateTest that a push happened and lets GateTest POST results back via
 * the existing inbound webhook at `/api/hooks/gatetest`. Never throws,
 * never blocks the push. 10-second timeout so a slow GateTest endpoint
 * can't hang the post-receive hook chain.
 *
 * Was a stub before 2026-05-16; `src/hooks/post-receive.ts:80` had the
 * comment "triggerGateTest helper is slated for the intelligence
 * rework" but nothing called it. CLAUDE.md claims "git push POSTs to
 * it" — this restores that contract.
 */
// One-shot warning latch — operators only need to be told once that
// GateTest is misconfigured. Reset between tests via the export below.
let _gatetestAuthWarned = false;
export function _resetGateTestAuthWarning(): void {
  _gatetestAuthWarned = false;
}

export async function notifyGateTestOfPush(
  owner: string,
  repo: string,
  ref: string,
  headSha: string
): Promise<void> {
  if (!process.env.GATETEST_URL) return;
  try {
    const headers: Record<string, string> = {
      "Content-Type": "application/json",
    };
    if (config.gatetestApiKey) {
      headers["Authorization"] = `Bearer ${config.gatetestApiKey}`;
    } else if (!_gatetestAuthWarned) {
      // GATETEST_URL is set but GATETEST_API_KEY is missing. GateTest
      // rejects unauthenticated requests with 401 — the scan never
      // actually runs but the push looks like it fired. Warn once so
      // operators notice (silent-fail audit, item §4 in AUDIT-v2.md).
      _gatetestAuthWarned = true;
      console.warn(
        "[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."
      );
    }
    const res = await fetch(config.gatetestUrl, {
      method: "POST",
      headers,
      body: JSON.stringify({
        repository: `${owner}/${repo}`,
        ref,
        sha: headSha,
        source: "gluecron",
        mode: "async",
      }),
      signal: AbortSignal.timeout(10_000),
    });
    if (!res.ok) {
      const body = await res.text().catch(() => "");
      console.warn(
        `[gatetest] push notify returned ${res.status} for ${owner}/${repo}@${headSha.slice(0, 7)}: ${body.slice(0, 200)}`
      );
    }
  } catch (err) {
    console.warn(
      `[gatetest] push notify failed for ${owner}/${repo}@${headSha.slice(0, 7)}:`,
      err instanceof Error ? err.message : err
    );
  }
}

/**
 * Run GateTest scan on a repository at a specific ref.
 */
export async function runGateTestScan(
  owner: string,
  repo: string,
  ref: string,
  headSha: string
): Promise<GateCheckResult> {
  if (!config.gatetestUrl) {
    return { name: "GateTest", passed: true, details: "GateTest URL not configured — skipped", skipped: true };
  }

  try {
    const headers: Record<string, string> = { "Content-Type": "application/json" };
    if (config.gatetestApiKey) {
      headers["Authorization"] = `Bearer ${config.gatetestApiKey}`;
    }

    const response = await fetch(config.gatetestUrl, {
      method: "POST",
      headers,
      body: JSON.stringify({
        repository: `${owner}/${repo}`,
        ref,
        sha: headSha,
        source: "gluecron",
        mode: "blocking",
      }),
      signal: AbortSignal.timeout(60_000),
    });

    if (!response.ok) {
      const body = await response.text().catch(() => "");
      return {
        name: "GateTest",
        passed: false,
        details: `GateTest returned ${response.status}: ${body.slice(0, 200)}`,
      };
    }

    const result = (await response.json().catch(() => ({}))) as Record<string, unknown>;
    const passed =
      result.passed === true || result.status === "passed" || result.status === "success";
    const summary =
      (result.summary as string) || (result.message as string) || (passed ? "All checks passed" : "Checks failed");
    return { name: "GateTest", passed, details: summary };
  } catch (err) {
    console.error("[gate] GateTest scan error:", err);
    return {
      name: "GateTest",
      passed: false,
      details: `GateTest scan failed: ${err instanceof Error ? err.message : "Unknown error"}`,
    };
  }
}

/**
 * Check for merge conflicts between branches.
 */
export async function checkMergeability(
  owner: string,
  repo: string,
  baseBranch: string,
  headBranch: string
): Promise<GateCheckResult> {
  const { getRepoPath } = await import("../git/repository");
  const repoDir = getRepoPath(owner, repo);

  function spawnGit(args: string[]) {
    try {
      return Bun.spawn(["git", ...args], { cwd: repoDir, stdout: "pipe", stderr: "pipe" });
    } catch {
      return null;
    }
  }

  const ffCheck = spawnGit(["merge-base", "--is-ancestor", baseBranch, headBranch]);
  if (!ffCheck) {
    return { name: "Merge check", passed: false, skipped: true, details: "Repository not accessible" };
  }
  const ffExit = await ffCheck.exited;
  if (ffExit === 0) {
    return { name: "Merge check", passed: true, details: "Fast-forward merge possible" };
  }

  const mergeBase = spawnGit(["merge-base", baseBranch, headBranch]);
  if (!mergeBase) {
    return { name: "Merge check", passed: false, details: "Branches have no common ancestor" };
  }
  const baseOut = await new Response(mergeBase.stdout).text();
  const baseExit = await mergeBase.exited;

  if (baseExit !== 0) {
    return { name: "Merge check", passed: false, details: "Branches have no common ancestor" };
  }

  const mergeTree = spawnGit(["merge-tree", baseOut.trim(), baseBranch, headBranch]);
  if (!mergeTree) {
    return { name: "Merge check", passed: false, details: "Branches have no common ancestor" };
  }
  const treeOut = await new Response(mergeTree.stdout).text();
  await mergeTree.exited;

  const hasConflicts = treeOut.includes("<<<<<<<");
  return {
    name: "Merge check",
    passed: !hasConflicts,
    details: hasConflicts
      ? "Merge conflicts detected — auto-resolution will be attempted"
      : "Clean merge possible",
  };
}

/**
 * Secret + security scan. Runs the regex scanner on files at the given ref,
 * then optionally runs the AI semantic scan on the diff.
 */
export async function runSecretAndSecurityScan(
  owner: string,
  repo: string,
  ref: string,
  headSha: string,
  opts: { scanSecrets: boolean; scanSecurity: boolean; diffText?: string }
): Promise<{
  secretResult: GateCheckResult;
  securityResult: GateCheckResult;
  secrets: SecretFinding[];
  securityIssues: SecurityFinding[];
}> {
  const { getRepoPath, getTree, getBlob, listBranches } = await import("../git/repository");
  const repoDir = getRepoPath(owner, repo);

  // Snapshot top-level + one level deep files at the ref
  const files: Array<{ path: string; content: string }> = [];
  const branches = await listBranches(owner, repo);
  const effectiveRef = branches.includes(ref.replace(/^refs\/heads\//, ""))
    ? ref.replace(/^refs\/heads\//, "")
    : headSha;

  async function walk(dir: string, depth: number): Promise<void> {
    if (depth > 4) return;
    const tree = await getTree(owner, repo, effectiveRef, dir);
    for (const entry of tree) {
      const full = dir ? `${dir}/${entry.name}` : entry.name;
      if (entry.type === "tree") {
        await walk(full, depth + 1);
      } else if (entry.type === "blob" && (entry.size ?? 0) < 200_000) {
        try {
          const blob = await getBlob(owner, repo, effectiveRef, full);
          if (blob && !blob.isBinary) {
            files.push({ path: full, content: blob.content });
          }
        } catch {
          // skip
        }
      }
      if (files.length >= 500) return;
    }
  }

  try {
    await walk("", 0);
  } catch {
    // Unable to walk — the ref may not exist yet. Bail gracefully.
  }

  const secrets = opts.scanSecrets ? scanForSecrets(files) : [];
  const securityIssues =
    opts.scanSecurity && opts.diffText ? await aiSecurityScan(`${owner}/${repo}`, opts.diffText) : [];

  const criticalSecrets = secrets.filter((s) => s.severity === "critical").length;
  const criticalSec = securityIssues.filter((i) => i.severity === "critical" || i.severity === "high").length;

  return {
    secretResult: {
      name: "Secret scan",
      passed: criticalSecrets === 0,
      details:
        secrets.length === 0
          ? "No secrets detected"
          : `Found ${secrets.length} secret${secrets.length === 1 ? "" : "s"} (${criticalSecrets} critical)`,
    },
    securityResult: {
      name: "Security scan",
      passed: criticalSec === 0,
      skipped: !opts.scanSecurity || !opts.diffText,
      details:
        securityIssues.length === 0
          ? opts.scanSecurity && opts.diffText
            ? "No security issues found"
            : "Skipped — no diff provided"
          : `Found ${securityIssues.length} issue${securityIssues.length === 1 ? "" : "s"} (${criticalSec} high/critical)`,
    },
    secrets,
    securityIssues,
  };
}

/**
 * Run every configured gate for a PR merge.
 * Records gate_runs entries. Optionally invokes auto-repair.
 */
export async function runAllGateChecks(
  owner: string,
  repo: string,
  baseBranch: string,
  headBranch: string,
  headSha: string,
  aiReviewApproved: boolean,
  opts: {
    pullRequestId?: string;
    enableAutoRepair?: boolean;
    diffText?: string;
  } = {}
): Promise<GateResult> {
  const started = Date.now();
  const repoRow = await lookupRepo(owner, repo);
  const settings = repoRow ? await getOrCreateSettings(repoRow.id) : null;

  // Decide which gates to run
  const runGateTest = settings?.gateTestEnabled !== false && !!config.gatetestUrl;
  const runSecretScan = settings?.secretScanEnabled !== false;
  const runSecurityScan = settings?.securityScanEnabled !== false;
  const runAiReview = settings?.aiReviewEnabled !== false;
  const enableRepair = opts.enableAutoRepair !== false && settings?.autoFixEnabled !== false;

  const [gateTestResult, mergeResult, scanResults] = await Promise.all([
    runGateTest
      ? runGateTestScan(owner, repo, `refs/heads/${headBranch}`, headSha)
      : Promise.resolve<GateCheckResult>({
          name: "GateTest",
          passed: true,
          skipped: true,
          details: "Disabled in settings",
        }),
    checkMergeability(owner, repo, baseBranch, headBranch),
    runSecretAndSecurityScan(owner, repo, `refs/heads/${headBranch}`, headSha, {
      scanSecrets: runSecretScan,
      scanSecurity: runSecurityScan,
      diffText: opts.diffText,
    }),
  ]);

  const checks: GateCheckResult[] = [gateTestResult];
  checks.push(scanResults.secretResult);
  if (runSecurityScan) checks.push(scanResults.securityResult);
  checks.push(mergeResult);
  checks.push({
    name: "AI Review",
    passed: !runAiReview || aiReviewApproved,
    skipped: !runAiReview,
    details: !runAiReview
      ? "Disabled in settings"
      : aiReviewApproved
        ? "AI review approved"
        : "AI review found blocking issues — resolve before merging",
  });

  // ---- Auto-repair on failures ----
  if (enableRepair) {
    // Secrets
    if (!scanResults.secretResult.passed) {
      const repair = await repairSecrets(owner, repo, headBranch, scanResults.secrets);
      if (repair.success) {
        scanResults.secretResult.passed = true;
        scanResults.secretResult.repaired = true;
        scanResults.secretResult.repairCommitSha = repair.commitSha;
        scanResults.secretResult.details = `Auto-redacted ${scanResults.secrets.length} secret${scanResults.secrets.length === 1 ? "" : "s"} (${repair.commitSha?.slice(0, 7)})`;
      }
    }
    // Security
    if (!scanResults.securityResult.passed && scanResults.securityIssues.length > 0) {
      const repair = await repairSecurityIssues(
        owner,
        repo,
        headBranch,
        scanResults.securityIssues
      );
      if (repair.success) {
        scanResults.securityResult.passed = true;
        scanResults.securityResult.repaired = true;
        scanResults.securityResult.repairCommitSha = repair.commitSha;
        scanResults.securityResult.details = `Auto-repaired ${repair.filesChanged.length} file${repair.filesChanged.length === 1 ? "" : "s"} (${repair.commitSha?.slice(0, 7)})`;
      }
    }
  }

  // Persist gate_runs
  if (repoRow) {
    const duration = Date.now() - started;
    await Promise.all(
      checks.map((check) =>
        recordGateRun({
          repositoryId: repoRow.id,
          pullRequestId: opts.pullRequestId,
          commitSha: headSha,
          ref: `refs/heads/${headBranch}`,
          gateName: check.name,
          status: check.skipped
            ? "skipped"
            : check.repaired
              ? "repaired"
              : check.passed
                ? "passed"
                : "failed",
          summary: check.details,
          repairAttempted: !!check.repaired,
          repairSucceeded: !!check.repaired,
          repairCommitSha: check.repairCommitSha,
          durationMs: duration,
        })
      )
    );
  }

  return {
    allPassed: checks.every((c) => c.passed || c.skipped),
    checks,
  };
}