Pre-launch — Gluecron is in final validation. Public signups and git hosting for non-owner users open after launch review.
CodeIssuesPull RequestsActionsSecurityInsightsSettings
✨ AI
More
Blame · Line-by-line history

post-receive.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.

post-receive.tsBlame806 lines · 3 contributors
fc1817aClaude1/**
2 * Post-receive hook logic.
2c34075Claude3 *
4 * Called after every successful git push. This is gluecron's intelligence layer:
5 * 1. Auto-repair — fix common issues and commit automatically
6 * 2. Push analysis — detect breaking changes, security issues
7 * 3. Health score — recompute repo health
8 * 4. GateTest scan — external security scanning
9 * 5. Crontech deploy — auto-deploy on push to main
10 * 6. Webhooks — fire registered webhook URLs
fc1817aClaude11 */
12
ba93444Claude13import { createHmac } from "crypto";
3ef4c9dClaude14import { and, eq } from "drizzle-orm";
fc1817aClaude15import { config } from "../lib/config";
2c34075Claude16import { autoRepair } from "../lib/autorepair";
170ddb2Claude17import { notifyGateTestOfPush } from "../lib/gate";
2c34075Claude18import { analyzePush, computeHealthScore } from "../lib/intelligence";
0316dbbClaude19import { db } from "../db";
20import { deployments, repositories, users } from "../db/schema";
21import { onDeployFailure } from "../lib/ai-incident";
a686079Claude22import {
23 commitsBetween,
24 getDefaultBranch,
25 getRepoPath,
26} from "../git/repository";
27import { indexChangedFiles } from "../lib/semantic-index";
6efae38Claude28import { scanDiffForIssues } from "../lib/ai-auto-issues";
4bbacbeClaude29import { enqueuePreviewBuild } from "../lib/branch-previews";
da3fc18Claude30import { scanDependencies } from "../lib/dependency-scanner";
d199847Claude31import { runDocDriftCheckForRepo } from "../lib/ai-doc-updater";
783dd46Claude32import {
33 findTargetsForPush,
34 finishDeployRow,
35 resolveEnv,
36 startDeployRow,
37} from "../lib/server-target-store";
38import { deployToTarget } from "../lib/server-targets";
c9ed210Claude39import { fireCloudDeploys } from "../lib/cloud-deploy";
fc1817aClaude40
41interface PushRef {
42 oldSha: string;
43 newSha: string;
44 refName: string;
45}
46
47export async function onPostReceive(
48 owner: string,
49 repo: string,
6efae38Claude50 refs: PushRef[],
51 pusherUserId: string = ""
fc1817aClaude52): Promise<void> {
2c34075Claude53 for (const ref of refs) {
54 if (ref.newSha.startsWith("0000")) continue; // Branch deletion
55 const branchName = ref.refName.replace("refs/heads/", "");
fc1817aClaude56
2c34075Claude57 // 1. Auto-repair (runs first, may create a new commit)
58 try {
59 const repair = await autoRepair(owner, repo, branchName);
60 if (repair.repaired) {
61 console.log(
62 `[autorepair] ${owner}/${repo}@${branchName}: ${repair.repairs.length} repairs committed`
63 );
64 }
65 } catch (err) {
66 console.error(`[autorepair] error:`, err);
67 }
fc1817aClaude68
2c34075Claude69 // 2. Push analysis
70 try {
71 const analysis = await analyzePush(owner, repo, ref.oldSha, ref.newSha);
72 console.log(
73 `[push-analysis] ${owner}/${repo}: ${analysis.summary}`
74 );
75 if (analysis.riskScore > 50) {
76 console.warn(
77 `[push-analysis] HIGH RISK push detected (score: ${analysis.riskScore})`
78 );
79 }
80 if (analysis.breakingChangeSignals.length > 0) {
81 console.warn(
82 `[push-analysis] Breaking changes: ${analysis.breakingChangeSignals.join("; ")}`
83 );
84 }
85 } catch (err) {
86 console.error(`[push-analysis] error:`, err);
87 }
88
89 // 3. Health score (async, don't block)
90 computeHealthScore(owner, repo).then((report) => {
91 console.log(
92 `[health] ${owner}/${repo}: ${report.grade} (${report.score}/100)`
93 );
94 }).catch((err) => {
95 console.error(`[health] error:`, err);
96 });
97 }
98
170ddb2Claude99 // 4. GateTest scan — fire-and-forget notification on every push. The
100 // helper short-circuits if `GATETEST_URL` is unset, so non-GateTest
101 // deployments pay no overhead. Results flow back via the inbound
102 // webhook at POST /api/hooks/gatetest.
103 for (const ref of refs) {
104 if (ref.newSha.startsWith("0000")) continue;
105 notifyGateTestOfPush(owner, repo, ref.refName, ref.newSha).catch((err) =>
106 console.warn("[gatetest] notify error:", err)
107 );
108 }
2c34075Claude109
a686079Claude110 // 4b. Continuous semantic index — embed changed files on every push so
111 // /api/v2/.../semantic-search has fresh vectors. Fire-and-forget;
112 // all failures are swallowed inside semantic-index.ts so a missing
113 // pgvector extension or absent embeddings API key never breaks the
114 // push path. Capped to MAX_FILES_PER_PUSH inside the lib.
115 for (const ref of refs) {
116 if (ref.newSha.startsWith("0000")) continue;
117 void fireSemanticIndex(owner, repo, ref.oldSha, ref.newSha).catch((err) =>
118 console.warn("[semantic-index] dispatch error:", err)
119 );
120 }
121
4bbacbeClaude122 // 4c. Per-branch preview URLs (migration 0062). Every push to a
123 // non-default branch enqueues a preview-build row. Gated on
124 // repositories.preview_builds_enabled (default on) so owners can
125 // opt out per-repo via repo-settings. Fire-and-forget; failures
126 // never break the push path.
127 void firePreviewBuilds(owner, repo, refs).catch((err) =>
128 console.warn("[branch-previews] dispatch error:", err)
129 );
130
6efae38Claude131 // 4e. AI Auto-Issue Opener. Scans the diff for each pushed ref for
132 // TODO/FIXME/HACK comments, hardcoded secrets, SQL injection patterns,
133 // and debug console.log calls. Opens one issue per finding type per
134 // file (capped at MAX_ISSUES_PER_PUSH). Gated on AI_AUTO_ISSUES=1.
135 // Fire-and-forget; never blocks the push path.
136 for (const ref of refs) {
137 if (ref.newSha.startsWith("0000")) continue;
138 scanDiffForIssues(owner, repo, ref.oldSha, ref.newSha, pusherUserId).catch(
139 (err) => console.warn("[ai-auto-issues] dispatch error:", err)
140 );
141 }
142
da3fc18Claude143 // 4f. Dependency CVE scanner — when DEPENDENCY_SCAN_ENABLED=1, scan
144 // every push that touches a recognized manifest file (package.json,
145 // requirements.txt, Cargo.toml, go.mod, Gemfile). Auto-opens issues
146 // for critical/high findings and updates a weekly digest for
147 // medium/low. Fire-and-forget; never blocks the push path.
148 if (config.dependencyScanEnabled) {
149 void fireDependencyScan(owner, repo, refs).catch((err) =>
150 console.warn("[dependency-scanner] dispatch error:", err)
151 );
152 }
153
d199847Claude154 // 4d. AI-tracked documentation drift check (migration 0068). Walks the
155 // repo's markdown files for `<!-- gluecron:doc-track ... -->`
156 // regions, hashes the referenced source, and opens a PR labelled
157 // `ai:doc-update` when the prose drifts. Fire-and-forget; failures
158 // are swallowed inside ai-doc-updater.ts so a missing anthropic key
159 // or empty doc_tracking table never breaks the push.
160 void fireDocDriftCheck(owner, repo).catch((err) =>
161 console.warn("[ai-doc-updater] dispatch error:", err)
162 );
163
ba93444Claude164 // 5. Crontech deploy (BLK-016) — only fires for the configured Crontech repo
165 // (CRONTECH_REPO, default `ccantynz-alt/crontech`) on a push to its
166 // default branch. The branch case (`Main` vs `main`) is determined by
167 // the bare repo's HEAD, not hardcoded.
168 if (`${owner}/${repo}` === config.crontechRepo) {
a28cedeClaude169 let defaultBranch =
170 (await getDefaultBranch(owner, repo).catch((err) => {
171 console.warn(
172 `[post-receive] getDefaultBranch failed for ${owner}/${repo}, defaulting to "main":`,
173 err instanceof Error ? err.message : err
174 );
175 return null;
176 })) || "main";
ba93444Claude177 const targetRef = `refs/heads/${defaultBranch}`;
178 const deployPush = refs.find(
179 (r) => r.refName === targetRef && !r.newSha.startsWith("0000")
180 );
181 if (deployPush) {
182 let repositoryId = "";
183 try {
184 const [row] = await db
185 .select({ id: repositories.id })
186 .from(repositories)
187 .innerJoin(users, eq(repositories.ownerId, users.id))
188 .where(and(eq(users.username, owner), eq(repositories.name, repo)))
189 .limit(1);
190 repositoryId = row?.id || "";
191 } catch {
192 /* ignore */
193 }
194 if (repositoryId) {
195 triggerCrontechDeploy({
196 owner,
197 repo,
198 before: deployPush.oldSha,
199 after: deployPush.newSha,
200 ref: targetRef,
201 branch: defaultBranch,
202 repositoryId,
203 }).catch((err: unknown) => console.error(`[crontech] error:`, err));
204 }
0316dbbClaude205 }
fc1817aClaude206 }
f2c00b4CC LABS App207
783dd46Claude208 // 5b. Block ST — Server targets. After core post-receive work, fire
209 // deploys against any `server_targets` row whose
210 // (watched_repository_id, watched_branch) matches a pushed ref.
211 // Fire-and-forget; deploy results land in `server_target_deployments`
212 // and the UI at /admin/servers/:id surfaces them.
213 void fireServerTargetDeploys(owner, repo, refs).catch((err) =>
214 console.warn("[server-targets] dispatch error:", err)
215 );
216
c9ed210Claude217 // 5c. Cloud deploy integrations (migration 0077). Fire push-triggered
218 // deploys to Fly.io, Railway, Render, Vercel, Netlify, or a generic
219 // webhook for any cloud_deploy_configs rows matching the pushed branch.
220 // Fire-and-forget; all failures are swallowed so the push path is
221 // never blocked.
222 void fireCloudDeploys(owner, repo, refs).catch((err) =>
223 console.warn("[cloud-deploy] dispatch error:", err)
224 );
225
f2c00b4CC LABS App226 // 6. BLOCK W — Self-host. When Gluecron.com itself receives a push to
227 // main, fire the local deploy via scripts/self-deploy.sh. The script
228 // forks into the background, so this call returns immediately (git
229 // push doesn't block). Gated on env SELF_HOST_REPO (set on the box) to
230 // avoid firing on customer repos that happen to be named "Gluecron.com".
231 const selfHostRepo = process.env.SELF_HOST_REPO;
232 if (selfHostRepo && `${owner}/${repo}` === selfHostRepo) {
233 const mainRef = refs.find(
234 (r) => r.refName === "refs/heads/main" && !r.newSha.startsWith("0000")
235 );
236 if (mainRef) {
237 const scriptPath =
238 process.env.GLUECRON_SELF_DEPLOY_SCRIPT ||
239 "/opt/gluecron/scripts/self-deploy.sh";
240 try {
241 const child = __selfHostSpawn(
242 [scriptPath, mainRef.oldSha, mainRef.newSha],
243 { stdout: "ignore", stderr: "ignore", stdin: "ignore" }
244 );
245 try {
246 (child as any)?.unref?.();
247 } catch {
248 /* unref optional */
249 }
250 console.log(
251 `[self-host] dispatched self-deploy for ${owner}/${repo}@${mainRef.newSha.slice(0, 7)}`
252 );
253 } catch (err) {
254 console.error(`[self-host] failed to spawn:`, err);
255 }
256 }
257 }
258}
259
260// BLOCK W — DI seam so the test suite can capture the spawn call without
261// actually shelling out to /opt/gluecron/scripts/self-deploy.sh. Production
262// callers go straight to Bun.spawn.
bf19c50Test User263const __defaultSelfHostSpawn: (cmd: string[], opts: any) => any = (cmd, opts) =>
f2c00b4CC LABS App264 Bun.spawn(cmd, opts);
bf19c50Test User265let __selfHostSpawn: (cmd: string[], opts: any) => any = __defaultSelfHostSpawn;
266/**
267 * Test-only: replace the spawn impl. Pass `null` to reset to Bun.spawn.
268 */
269export function __setSelfHostSpawnForTests(
270 fn: typeof __selfHostSpawn | null
271): void {
272 __selfHostSpawn = fn ?? __defaultSelfHostSpawn;
fc1817aClaude273}
274
43cf9b0Claude275/**
ba93444Claude276 * BLK-016 — outbound deploy webhook for Crontech's deploy-agent.
43cf9b0Claude277 *
ba93444Claude278 * Wire contract (matches Crontech's `apps/api/src/webhooks/gluecron-push.ts`):
43cf9b0Claude279 *
ba93444Claude280 * POST https://crontech.ai/api/webhooks/gluecron-push
43cf9b0Claude281 * Content-Type: application/json
ba93444Claude282 * X-Gluecron-Signature: sha256=<hex(hmac-sha256(body, GLUECRON_WEBHOOK_SECRET))>
43cf9b0Claude283 *
284 * {
ba93444Claude285 * "event": "push",
286 * "repository": { "full_name": "ccantynz-alt/crontech" },
287 * "ref": "refs/heads/Main",
288 * "after": "<40-hex commit SHA>",
289 * "before": "<40-hex previous SHA>",
290 * "pusher": { "name": "<author>", "email": "<email>" },
291 * "commits": [ { "id": "<sha>", "message": "<msg>", "timestamp": "<iso8601>" } ]
43cf9b0Claude292 * }
293 *
ba93444Claude294 * The `after` SHA is the dedupe key on the receiver side (idempotent).
43cf9b0Claude295 *
ba93444Claude296 * Delivery: at-least-once via exponential-backoff retry. Up to 5 attempts at
297 * delays 1s / 4s / 16s / 64s / 256s; first 2xx wins. If `GLUECRON_WEBHOOK_SECRET`
298 * is unset the signature header is omitted and Crontech is expected to reject —
299 * we still record the deploy row as failed.
43cf9b0Claude300 */
ba93444Claude301const RETRY_DELAYS_MS = [1_000, 4_000, 16_000, 64_000, 256_000];
302
303interface TriggerArgs {
304 owner: string;
305 repo: string;
306 before: string;
307 after: string;
308 ref: string;
309 branch: string;
310 repositoryId: string;
311}
312
313interface TriggerOptions {
314 fetchImpl?: typeof fetch;
315 sleep?: (ms: number) => Promise<void>;
316 retryDelaysMs?: number[];
317 now?: () => Date;
318}
319
320function signBody(body: string, secret: string): string | null {
321 if (!secret) return null;
322 return "sha256=" + createHmac("sha256", secret).update(body).digest("hex");
323}
324
325async function buildPayload(args: TriggerArgs, now: Date): Promise<{
326 payload: Record<string, unknown>;
327 pusherName: string;
328 pusherEmail: string;
329}> {
330 // Walk commits new since the last push. Cap at 50 like GitHub's webhook.
331 // `before` may be all-zeros for a first push to the branch — commitsBetween
332 // handles that by treating null `from` as "everything reachable from `to`".
333 const fromSha = /^0+$/.test(args.before) ? null : args.before;
334 let commits: Array<{ id: string; message: string; timestamp: string }> = [];
335 let pusherName = "gluecron";
336 let pusherEmail = "noreply@gluecron.local";
337 try {
338 const list = await commitsBetween(args.owner, args.repo, fromSha, args.after);
339 commits = list.slice(0, 50).map((c) => ({
340 id: c.sha,
341 message: c.message,
342 timestamp: c.date,
343 }));
344 if (list[0]) {
345 pusherName = list[0].author || pusherName;
346 pusherEmail = list[0].authorEmail || pusherEmail;
347 }
348 } catch {
349 /* ignore — payload still valid with empty commits[] */
350 }
351 return {
352 payload: {
353 event: "push",
354 repository: { full_name: `${args.owner}/${args.repo}` },
355 ref: args.ref,
356 after: args.after,
357 before: args.before,
358 pusher: { name: pusherName, email: pusherEmail },
359 commits,
360 // Ancillary fields — receiver may ignore but they're useful for logs:
361 sent_at: now.toISOString(),
362 source: "gluecron",
363 },
364 pusherName,
365 pusherEmail,
366 };
367}
368
fc1817aClaude369async function triggerCrontechDeploy(
ba93444Claude370 args: TriggerArgs,
371 opts: TriggerOptions = {}
fc1817aClaude372): Promise<void> {
ba93444Claude373 const fetchImpl = opts.fetchImpl ?? fetch;
374 const sleep = opts.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
375 const delays = opts.retryDelaysMs ?? RETRY_DELAYS_MS;
376 const now = opts.now ?? (() => new Date());
377
3ef4c9dClaude378 let deployId = "";
fc1817aClaude379 try {
3ef4c9dClaude380 const [row] = await db
381 .insert(deployments)
382 .values({
ba93444Claude383 repositoryId: args.repositoryId,
3ef4c9dClaude384 environment: "production",
ba93444Claude385 commitSha: args.after,
386 ref: args.ref,
3ef4c9dClaude387 status: "pending",
388 target: "crontech",
389 })
390 .returning();
391 deployId = row?.id || "";
392 } catch {
393 /* ignore */
fc1817aClaude394 }
395
ba93444Claude396 const { payload } = await buildPayload(args, now());
397 const body = JSON.stringify(payload);
398 const signature = signBody(body, config.gluecronWebhookSecret);
399
400 const headers: Record<string, string> = {
401 "Content-Type": "application/json",
402 "User-Agent": "gluecron-webhook/1",
403 "X-Gluecron-Event": "push",
404 "X-Gluecron-Delivery": cryptoRandomId(),
405 };
406 if (signature) headers["X-Gluecron-Signature"] = signature;
407
408 let lastStatus = 0;
409 let lastError = "";
410 let success = false;
411
412 // Up to delays.length + 1 attempts (initial try + each delay).
413 const totalAttempts = delays.length + 1;
414 for (let attempt = 0; attempt < totalAttempts; attempt++) {
415 try {
416 const response = await fetchImpl(config.crontechDeployUrl, {
417 method: "POST",
418 headers,
419 body,
420 });
421 lastStatus = response.status;
422 console.log(
423 `[crontech] attempt ${attempt + 1}/${totalAttempts} → ${lastStatus} for ${args.owner}/${args.repo}@${args.after.slice(0, 7)}`
424 );
425 if (response.ok) {
426 success = true;
427 break;
428 }
429 // 4xx (except 408/429) is unrecoverable — stop retrying.
430 if (response.status >= 400 && response.status < 500 &&
431 response.status !== 408 && response.status !== 429) {
432 break;
433 }
434 } catch (err) {
435 lastError = err instanceof Error ? err.message : String(err);
436 console.error(
437 `[crontech] attempt ${attempt + 1}/${totalAttempts} failed: ${lastError}`
438 );
3ef4c9dClaude439 }
ba93444Claude440 const nextDelay = delays[attempt];
441 if (nextDelay !== undefined && attempt < totalAttempts - 1) {
442 await sleep(nextDelay);
1e162a8Claude443 }
ba93444Claude444 }
445
446 if (deployId) {
447 try {
3ef4c9dClaude448 await db
449 .update(deployments)
450 .set({
ba93444Claude451 status: success ? "success" : "failed",
452 blockedReason: success
453 ? null
454 : (lastError ? lastError : `HTTP ${lastStatus}`),
3ef4c9dClaude455 completedAt: new Date(),
456 })
457 .where(eq(deployments.id, deployId));
ba93444Claude458 } catch {
459 /* ignore */
3ef4c9dClaude460 }
461 }
462
ba93444Claude463 if (!success && deployId) {
464 void onDeployFailure({
465 repositoryId: args.repositoryId,
466 deploymentId: deployId,
467 ref: args.ref,
468 commitSha: args.after,
469 target: "crontech",
470 errorMessage: lastError || `HTTP ${lastStatus}`,
471 }).catch((e) => console.error("[ai-incident]", e));
fc1817aClaude472 }
473}
43cf9b0Claude474
ba93444Claude475function cryptoRandomId(): string {
476 // Short opaque delivery ID for log correlation. Not security-sensitive.
477 const bytes = new Uint8Array(8);
478 crypto.getRandomValues(bytes);
479 return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
480}
481
a686079Claude482/**
483 * Resolve `owner/repo` to its DB repository.id and dispatch the
484 * semantic-index update. Pulls the list of changed paths via
485 * `git diff --name-only`, dropping any deletions (handled implicitly
486 * because deleted blobs simply don't resolve in `indexChangedFiles`).
487 *
488 * Never throws — exhaust every external call inside a try/catch so the
489 * push completes even if Postgres or the embedding API is down.
490 */
491async function fireSemanticIndex(
492 owner: string,
493 repo: string,
494 oldSha: string,
495 newSha: string
496): Promise<void> {
497 let repositoryId = "";
498 try {
499 const [row] = await db
500 .select({ id: repositories.id })
501 .from(repositories)
502 .innerJoin(users, eq(repositories.ownerId, users.id))
503 .where(and(eq(users.username, owner), eq(repositories.name, repo)))
504 .limit(1);
505 repositoryId = row?.id || "";
506 } catch {
507 return;
508 }
509 if (!repositoryId) return;
510
511 let changedPaths: string[] = [];
512 try {
513 changedPaths = await listChangedPaths(owner, repo, oldSha, newSha);
514 } catch {
515 return;
516 }
517 if (!changedPaths.length) return;
518
519 try {
520 const out = await indexChangedFiles({
521 repositoryId,
522 ownerName: owner,
523 repoName: repo,
524 commitSha: newSha,
525 changedPaths,
526 });
527 if (out.indexed > 0) {
528 console.log(
529 `[semantic-index] ${owner}/${repo}@${newSha.slice(0, 7)}: indexed ${out.indexed} file(s) via ${out.model}`
530 );
531 }
532 } catch (err) {
533 console.warn("[semantic-index] indexChangedFiles error:", err);
534 }
535}
536
537/**
538 * Returns the list of files touched between `oldSha` and `newSha`. For
539 * the initial push on a branch (oldSha all-zero) we walk every file in
540 * the new tree via `git ls-tree -r`. Returns [] on any subprocess error.
541 */
542async function listChangedPaths(
543 owner: string,
544 repo: string,
545 oldSha: string,
546 newSha: string
547): Promise<string[]> {
548 const cwd = getRepoPath(owner, repo);
549 const allZero = /^0+$/.test(oldSha);
550 const cmd = allZero
551 ? ["git", "ls-tree", "-r", "--name-only", newSha]
552 : ["git", "diff", "--name-only", oldSha, newSha];
553 try {
554 const proc = Bun.spawn(cmd, {
555 cwd,
556 stdout: "pipe",
557 stderr: "pipe",
558 });
559 const text = await new Response(proc.stdout).text();
560 await proc.exited;
561 return text
562 .split("\n")
563 .map((s) => s.trim())
564 .filter((s) => s.length > 0);
565 } catch {
566 return [];
567 }
568}
569
4bbacbeClaude570/**
571 * Migration 0062 — fan out push refs to enqueuePreviewBuild for every
572 * non-default branch on a `preview_builds_enabled` repo.
573 *
574 * Resolves the repo row once, fetches the default branch + opt-out flag,
575 * then upserts one preview row per pushed ref that isn't the default.
576 * Branch deletions (oldSha all-zero or newSha all-zero with oldSha set)
577 * are skipped — they shouldn't create preview rows. Never throws.
578 */
579async function firePreviewBuilds(
580 owner: string,
581 repo: string,
582 refs: PushRef[]
583): Promise<void> {
584 // Filter to live branch pushes only.
585 const branchRefs = refs.filter(
586 (r) =>
587 r.refName.startsWith("refs/heads/") && !r.newSha.startsWith("0000")
588 );
589 if (branchRefs.length === 0) return;
590
591 let repoRow: { id: string; previewBuildsEnabled: boolean; defaultBranch: string } | null = null;
592 try {
593 const [row] = await db
594 .select({
595 id: repositories.id,
596 previewBuildsEnabled: repositories.previewBuildsEnabled,
597 defaultBranch: repositories.defaultBranch,
598 })
599 .from(repositories)
600 .innerJoin(users, eq(repositories.ownerId, users.id))
601 .where(and(eq(users.username, owner), eq(repositories.name, repo)))
602 .limit(1);
603 repoRow = row || null;
604 } catch {
605 return;
606 }
607 if (!repoRow) return;
608 if (!repoRow.previewBuildsEnabled) return;
609
610 for (const ref of branchRefs) {
611 const branchName = ref.refName.replace("refs/heads/", "");
612 if (branchName === repoRow.defaultBranch) continue;
613 try {
614 await enqueuePreviewBuild({
615 repositoryId: repoRow.id,
616 ownerName: owner,
617 repoName: repo,
618 branchName,
619 commitSha: ref.newSha,
620 });
621 } catch (err) {
622 console.warn(
623 `[branch-previews] enqueue failed for ${owner}/${repo}@${branchName}:`,
624 err instanceof Error ? err.message : err
625 );
626 }
627 }
628}
629
d199847Claude630/**
631 * Migration 0068 — resolve `owner/repo` to its DB id and kick off the
632 * doc-drift sweep (findTrackedDocs + proposeDocUpdate). Returns immediately
633 * on missing repo or DB error — pushes never block. Never throws.
634 */
635async function fireDocDriftCheck(owner: string, repo: string): Promise<void> {
636 let repositoryId = "";
637 try {
638 const [row] = await db
639 .select({ id: repositories.id })
640 .from(repositories)
641 .innerJoin(users, eq(repositories.ownerId, users.id))
642 .where(and(eq(users.username, owner), eq(repositories.name, repo)))
643 .limit(1);
644 repositoryId = row?.id || "";
645 } catch {
646 return;
647 }
648 if (!repositoryId) return;
649 try {
650 const out = await runDocDriftCheckForRepo(repositoryId);
651 if (out.docs > 0 || out.proposed > 0) {
652 console.log(
653 `[ai-doc-updater] ${owner}/${repo}: docs=${out.docs} proposed=${out.proposed}`
654 );
655 }
656 } catch (err) {
657 console.warn("[ai-doc-updater] runDocDriftCheckForRepo error:", err);
658 }
659}
660
783dd46Claude661/**
662 * Block ST — fan out the push to any server targets that watch this
663 * (repo, branch). One sequential deploy per target so a slow box can't
664 * stall the next push, but multiple matching targets run in parallel.
665 * Every failure is contained to its own deploy row + console warn —
666 * nothing here can break the push path.
667 */
668async function fireServerTargetDeploys(
669 owner: string,
670 repo: string,
671 refs: PushRef[]
672): Promise<void> {
673 const liveRefs = refs.filter(
674 (r) => r.refName.startsWith("refs/heads/") && !r.newSha.startsWith("0000")
675 );
676 if (liveRefs.length === 0) return;
677
678 let repositoryId = "";
679 try {
680 const [row] = await db
681 .select({ id: repositories.id })
682 .from(repositories)
683 .innerJoin(users, eq(repositories.ownerId, users.id))
684 .where(and(eq(users.username, owner), eq(repositories.name, repo)))
685 .limit(1);
686 repositoryId = row?.id || "";
687 } catch {
688 return;
689 }
690 if (!repositoryId) return;
691
692 await Promise.all(
693 liveRefs.map(async (ref) => {
694 const branch = ref.refName.replace("refs/heads/", "");
695 let targets;
696 try {
697 targets = await findTargetsForPush({ repositoryId, branch });
698 } catch {
699 return;
700 }
701 if (!targets.length) return;
702
703 await Promise.all(
704 targets.map(async (target) => {
705 try {
706 const env = await resolveEnv(target.id);
707 const deployId = await startDeployRow({
708 targetId: target.id,
709 commitSha: ref.newSha,
710 ref: ref.refName,
711 triggerSource: "push",
712 });
713 const result = await deployToTarget(target, {
714 commitSha: ref.newSha,
715 ref: ref.refName,
716 env,
717 });
718 if (deployId) {
719 await finishDeployRow({
720 id: deployId,
721 exitCode: result.exitCode,
722 stdout: result.stdout,
723 stderr: result.stderr,
724 });
725 }
726 console.log(
727 `[server-targets] ${target.name} @ ${ref.newSha.slice(0, 7)}: exit ${result.exitCode}`
728 );
729 } catch (err) {
730 console.warn(
731 `[server-targets] ${target.name}: deploy threw — ${err instanceof Error ? err.message : err}`
732 );
733 }
734 })
735 );
736 })
737 );
738}
739
da3fc18Claude740/**
741 * Fire-and-forget wrapper around scanDependencies for each pushed ref.
742 * Resolves the repo DB row once, then runs the scanner on each live push.
743 * Swallows all errors so a scanner failure never affects the push path.
744 */
745async function fireDependencyScan(
746 owner: string,
747 repo: string,
748 refs: PushRef[]
749): Promise<void> {
750 const liveRefs = refs.filter(
751 (r) => r.refName.startsWith("refs/heads/") && !r.newSha.startsWith("0000")
752 );
753 if (liveRefs.length === 0) return;
754
755 let repoRow: { id: string; ownerId: string } | null = null;
756 try {
757 const [row] = await db
758 .select({ id: repositories.id, ownerId: repositories.ownerId })
759 .from(repositories)
760 .innerJoin(users, eq(repositories.ownerId, users.id))
761 .where(and(eq(users.username, owner), eq(repositories.name, repo)))
762 .limit(1);
763 repoRow = row || null;
764 } catch {
765 return;
766 }
767 if (!repoRow) return;
768
769 for (const ref of liveRefs) {
770 try {
771 const findings = await scanDependencies(
772 repoRow.id,
773 owner,
774 repo,
775 ref.newSha,
776 ref.oldSha,
777 repoRow.ownerId
778 );
779 if (findings.length > 0) {
780 console.log(
781 `[dependency-scanner] ${owner}/${repo}@${ref.newSha.slice(0, 7)}: ${findings.length} finding(s)`
782 );
783 }
784 } catch (err) {
785 console.warn(
786 `[dependency-scanner] scan threw for ${owner}/${repo}@${ref.newSha.slice(0, 7)}:`,
787 err instanceof Error ? err.message : err
788 );
789 }
790 }
791}
792
43cf9b0Claude793/** Test-only access to internal helpers. */
a686079Claude794export const __test = {
795 triggerCrontechDeploy,
796 signBody,
797 buildPayload,
798 RETRY_DELAYS_MS,
799 listChangedPaths,
800 fireSemanticIndex,
4bbacbeClaude801 firePreviewBuilds,
d199847Claude802 fireDocDriftCheck,
783dd46Claude803 fireServerTargetDeploys,
da3fc18Claude804 fireDependencyScan,
c9ed210Claude805 fireCloudDeploys,
a686079Claude806};