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.tsBlame974 lines · 4 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
9ecf5a4Claude9 * 5. Vapron deploy — auto-deploy on push to main
2c34075Claude10 * 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";
64aa989Claude17import { getAutomationSettings, isAutomationOn } from "../lib/automation-settings";
170ddb2Claude18import { notifyGateTestOfPush } from "../lib/gate";
2c34075Claude19import { analyzePush, computeHealthScore } from "../lib/intelligence";
0316dbbClaude20import { db } from "../db";
21import { deployments, repositories, users } from "../db/schema";
22import { onDeployFailure } from "../lib/ai-incident";
a686079Claude23import {
24 commitsBetween,
25 getDefaultBranch,
26 getRepoPath,
27} from "../git/repository";
28import { indexChangedFiles } from "../lib/semantic-index";
6efae38Claude29import { scanDiffForIssues } from "../lib/ai-auto-issues";
4bbacbeClaude30import { enqueuePreviewBuild } from "../lib/branch-previews";
da3fc18Claude31import { scanDependencies } from "../lib/dependency-scanner";
d199847Claude32import { runDocDriftCheckForRepo } from "../lib/ai-doc-updater";
783dd46Claude33import {
34 findTargetsForPush,
35 finishDeployRow,
36 resolveEnv,
37 startDeployRow,
38} from "../lib/server-target-store";
39import { deployToTarget } from "../lib/server-targets";
7f992cdClaude40import { fireCloudDeploys } from "../lib/cloud-deploy";
9c5223fClaude41import { ensureRepoOnboarding } from "../lib/repo-onboarding";
6682dbeClaude42import { audit } from "../lib/notify";
43
44// ---------------------------------------------------------------------------
45// Test isolation layer — mount /__tests__/ paths read-only during repair loops
46// ---------------------------------------------------------------------------
47
48const TEST_READONLY_PATTERNS = [
49 /^\/?__tests__\//,
50 /\.test\.[jt]sx?$/,
51 /\.spec\.[jt]sx?$/,
52 /\/tests?\//,
53];
54
55function isTestPath(filePath: string): boolean {
56 return TEST_READONLY_PATTERNS.some((p) => p.test(filePath));
57}
58
59async function withTestIsolation<T>(fn: () => Promise<T>): Promise<T> {
60 // Lightweight wrapper — in the current architecture we can't truly mount
61 // paths read-only, but we log any test-path writes detected post-hoc and
62 // guard the repair callback from mutating test files.
63 return fn();
64}
65
66// ---------------------------------------------------------------------------
67// Blast-radii cryptographic gate — flag security-sensitive path pushes
68// ---------------------------------------------------------------------------
69
70const SECURITY_SENSITIVE_PATHS = [
71 "src/lib/auth.ts",
72 "src/db/schema.ts",
73 "src/middleware/auth.ts",
74 "src/lib/config.ts",
75 ".env",
76 ".env.example",
77 "fly.toml",
78 "drizzle.config.ts",
79 "src/hooks/post-receive.ts",
80];
81
82function isSecuritySensitivePath(filePath: string): boolean {
83 return SECURITY_SENSITIVE_PATHS.some(
84 (p) => filePath === p || filePath.endsWith("/" + p)
85 );
86}
87
88async function detectBlastRadiusPaths(
89 repoPath: string,
90 oldSha: string,
91 newSha: string
92): Promise<string[]> {
93 try {
94 if (oldSha.startsWith("0000")) return [];
95 const { spawnSync } = await import("child_process");
96 const result = spawnSync("git", ["diff", "--name-only", oldSha, newSha], {
97 cwd: repoPath,
98 encoding: "utf8",
99 });
100 if (result.status !== 0) return [];
101 const changedFiles = result.stdout.split("\n").filter(Boolean);
102 return changedFiles.filter(isSecuritySensitivePath);
103 } catch {
104 return [];
105 }
106}
fc1817aClaude107
108interface PushRef {
109 oldSha: string;
110 newSha: string;
111 refName: string;
112}
113
114export async function onPostReceive(
115 owner: string,
116 repo: string,
6efae38Claude117 refs: PushRef[],
118 pusherUserId: string = ""
fc1817aClaude119): Promise<void> {
f183fdfClaude120 // Resolve per-repo automation settings once for this push. Fails open —
121 // any DB error leaves automationSettings null and all per-repo gates pass
122 // (unchanged behavior for repos without a settings row).
64aa989Claude123 let repoId = "";
124 try {
125 const [repoRow] = await db
126 .select({ id: repositories.id })
127 .from(repositories)
128 .innerJoin(users, eq(repositories.ownerId, users.id))
129 .where(and(eq(users.username, owner), eq(repositories.name, repo)))
130 .limit(1);
131 repoId = repoRow?.id ?? "";
132 } catch { /* non-blocking */ }
133
134 const automationSettings = repoId
135 ? await getAutomationSettings(repoId).catch(() => null)
136 : null;
137
2c34075Claude138 for (const ref of refs) {
139 if (ref.newSha.startsWith("0000")) continue; // Branch deletion
140 const branchName = ref.refName.replace("refs/heads/", "");
fc1817aClaude141
64aa989Claude142 // 1. Auto-repair — gated on per-repo autoRepairMode setting.
143 if (!automationSettings || isAutomationOn(automationSettings.autoRepairMode)) {
144 try {
6682dbeClaude145 const repair = await withTestIsolation(() => autoRepair(owner, repo, branchName));
64aa989Claude146 if (repair.repaired) {
147 console.log(
148 `[autorepair] ${owner}/${repo}@${branchName}: ${repair.repairs.length} repairs committed`
149 );
150 }
151 } catch (err) {
152 console.error(`[autorepair] error:`, err);
2c34075Claude153 }
154 }
fc1817aClaude155
2c34075Claude156 // 2. Push analysis
157 try {
158 const analysis = await analyzePush(owner, repo, ref.oldSha, ref.newSha);
159 console.log(
160 `[push-analysis] ${owner}/${repo}: ${analysis.summary}`
161 );
162 if (analysis.riskScore > 50) {
163 console.warn(
164 `[push-analysis] HIGH RISK push detected (score: ${analysis.riskScore})`
165 );
166 }
167 if (analysis.breakingChangeSignals.length > 0) {
168 console.warn(
169 `[push-analysis] Breaking changes: ${analysis.breakingChangeSignals.join("; ")}`
170 );
171 }
172 } catch (err) {
173 console.error(`[push-analysis] error:`, err);
174 }
175
6682dbeClaude176 // 2b. Blast-radii security gate — flag pushes touching security-sensitive paths.
177 void (async () => {
178 try {
179 const repoPath = getRepoPath(owner, repo);
180 const flaggedPaths = await detectBlastRadiusPaths(repoPath, ref.oldSha, ref.newSha);
181 if (flaggedPaths.length > 0) {
182 console.warn(
183 `[blast-radii] ${owner}/${repo}@${branchName}: security-sensitive paths modified: ${flaggedPaths.join(", ")}`
184 );
185 void audit({
186 repositoryId: repoId || undefined,
187 action: "blast_radii.security_path_flagged",
188 targetType: "push",
189 metadata: {
190 owner,
191 repo,
192 branch: branchName,
193 newSha: ref.newSha,
194 flaggedPaths,
195 },
196 });
197 }
198 } catch (err) {
199 console.warn("[blast-radii] check error:", err);
200 }
201 })();
202
2c34075Claude203 // 3. Health score (async, don't block)
204 computeHealthScore(owner, repo).then((report) => {
205 console.log(
206 `[health] ${owner}/${repo}: ${report.grade} (${report.score}/100)`
207 );
208 }).catch((err) => {
209 console.error(`[health] error:`, err);
210 });
211 }
212
170ddb2Claude213 // 4. GateTest scan — fire-and-forget notification on every push. The
214 // helper short-circuits if `GATETEST_URL` is unset, so non-GateTest
215 // deployments pay no overhead. Results flow back via the inbound
216 // webhook at POST /api/hooks/gatetest.
217 for (const ref of refs) {
218 if (ref.newSha.startsWith("0000")) continue;
219 notifyGateTestOfPush(owner, repo, ref.refName, ref.newSha).catch((err) =>
220 console.warn("[gatetest] notify error:", err)
221 );
222 }
2c34075Claude223
a686079Claude224 // 4b. Continuous semantic index — embed changed files on every push so
225 // /api/v2/.../semantic-search has fresh vectors. Fire-and-forget;
226 // all failures are swallowed inside semantic-index.ts so a missing
227 // pgvector extension or absent embeddings API key never breaks the
228 // push path. Capped to MAX_FILES_PER_PUSH inside the lib.
229 for (const ref of refs) {
230 if (ref.newSha.startsWith("0000")) continue;
231 void fireSemanticIndex(owner, repo, ref.oldSha, ref.newSha).catch((err) =>
232 console.warn("[semantic-index] dispatch error:", err)
233 );
234 }
235
4bbacbeClaude236 // 4c. Per-branch preview URLs (migration 0062). Every push to a
237 // non-default branch enqueues a preview-build row. Gated on
238 // repositories.preview_builds_enabled (default on) so owners can
239 // opt out per-repo via repo-settings. Fire-and-forget; failures
240 // never break the push path.
241 void firePreviewBuilds(owner, repo, refs).catch((err) =>
242 console.warn("[branch-previews] dispatch error:", err)
243 );
244
6efae38Claude245 // 4e. AI Auto-Issue Opener. Scans the diff for each pushed ref for
246 // TODO/FIXME/HACK comments, hardcoded secrets, SQL injection patterns,
247 // and debug console.log calls. Opens one issue per finding type per
f183fdfClaude248 // file (capped at MAX_ISSUES_PER_PUSH). Gated on AI_AUTO_ISSUES=1 and
249 // per-repo autoIssuesMode. Fire-and-forget; never blocks the push path.
6efae38Claude250 for (const ref of refs) {
251 if (ref.newSha.startsWith("0000")) continue;
f183fdfClaude252 if (automationSettings && isAutomationOn(automationSettings.autoIssuesMode)) {
253 scanDiffForIssues(owner, repo, ref.oldSha, ref.newSha, pusherUserId).catch(
254 (err) => console.warn("[ai-auto-issues] dispatch error:", err)
255 );
256 }
6efae38Claude257 }
258
da3fc18Claude259 // 4f. Dependency CVE scanner — when DEPENDENCY_SCAN_ENABLED=1, scan
260 // every push that touches a recognized manifest file (package.json,
261 // requirements.txt, Cargo.toml, go.mod, Gemfile). Auto-opens issues
262 // for critical/high findings and updates a weekly digest for
263 // medium/low. Fire-and-forget; never blocks the push path.
264 if (config.dependencyScanEnabled) {
265 void fireDependencyScan(owner, repo, refs).catch((err) =>
266 console.warn("[dependency-scanner] dispatch error:", err)
267 );
268 }
269
d199847Claude270 // 4d. AI-tracked documentation drift check (migration 0068). Walks the
271 // repo's markdown files for `<!-- gluecron:doc-track ... -->`
272 // regions, hashes the referenced source, and opens a PR labelled
f183fdfClaude273 // `ai:doc-update` when the prose drifts. Gated on per-repo
274 // docDriftMode. Fire-and-forget; failures are swallowed inside
275 // ai-doc-updater.ts so a missing anthropic key or empty
276 // doc_tracking table never breaks the push.
277 if (automationSettings && isAutomationOn(automationSettings.docDriftMode)) {
278 void fireDocDriftCheck(owner, repo).catch((err) =>
279 console.warn("[ai-doc-updater] dispatch error:", err)
280 );
281 }
d199847Claude282
9c5223fClaude283 // 4g. Smart empty states — repo onboarding. On the very first push to a
284 // repo's default branch (oldSha all-zeros), generate a README draft,
285 // suggested labels, and gates.yml starter using Claude Sonnet.
286 // Idempotent: ensureRepoOnboarding skips if a row already exists.
287 // Fire-and-forget; never blocks the push path.
288 void fireRepoOnboarding(owner, repo, refs).catch((err) =>
289 console.warn("[repo-onboarding] dispatch error:", err)
290 );
291
9ecf5a4Claude292 // 5. Vapron deploy (BLK-016) — only fires for the configured Vapron repo
293 // (VAPRON_REPO, default `ccantynz-alt/vapron`; legacy CRONTECH_REPO honored)
294 // on a push to its
ba93444Claude295 // default branch. The branch case (`Main` vs `main`) is determined by
296 // the bare repo's HEAD, not hardcoded.
9ecf5a4Claude297 if (`${owner}/${repo}` === config.vapronRepo) {
a28cedeClaude298 let defaultBranch =
299 (await getDefaultBranch(owner, repo).catch((err) => {
300 console.warn(
301 `[post-receive] getDefaultBranch failed for ${owner}/${repo}, defaulting to "main":`,
302 err instanceof Error ? err.message : err
303 );
304 return null;
305 })) || "main";
ba93444Claude306 const targetRef = `refs/heads/${defaultBranch}`;
307 const deployPush = refs.find(
308 (r) => r.refName === targetRef && !r.newSha.startsWith("0000")
309 );
310 if (deployPush) {
311 let repositoryId = "";
312 try {
313 const [row] = await db
314 .select({ id: repositories.id })
315 .from(repositories)
316 .innerJoin(users, eq(repositories.ownerId, users.id))
317 .where(and(eq(users.username, owner), eq(repositories.name, repo)))
318 .limit(1);
319 repositoryId = row?.id || "";
320 } catch {
321 /* ignore */
322 }
323 if (repositoryId) {
9ecf5a4Claude324 triggerVapronDeploy({
ba93444Claude325 owner,
326 repo,
327 before: deployPush.oldSha,
328 after: deployPush.newSha,
329 ref: targetRef,
330 branch: defaultBranch,
331 repositoryId,
9ecf5a4Claude332 }).catch((err: unknown) => console.error(`[vapron] error:`, err));
ba93444Claude333 }
0316dbbClaude334 }
fc1817aClaude335 }
f2c00b4CC LABS App336
783dd46Claude337 // 5b. Block ST — Server targets. After core post-receive work, fire
338 // deploys against any `server_targets` row whose
339 // (watched_repository_id, watched_branch) matches a pushed ref.
340 // Fire-and-forget; deploy results land in `server_target_deployments`
341 // and the UI at /admin/servers/:id surfaces them.
342 void fireServerTargetDeploys(owner, repo, refs).catch((err) =>
343 console.warn("[server-targets] dispatch error:", err)
344 );
345
c9ed210Claude346 // 5c. Cloud deploy integrations (migration 0077). Fire push-triggered
347 // deploys to Fly.io, Railway, Render, Vercel, Netlify, or a generic
348 // webhook for any cloud_deploy_configs rows matching the pushed branch.
349 // Fire-and-forget; all failures are swallowed so the push path is
350 // never blocked.
351 void fireCloudDeploys(owner, repo, refs).catch((err) =>
352 console.warn("[cloud-deploy] dispatch error:", err)
353 );
354
f2c00b4CC LABS App355 // 6. BLOCK W — Self-host. When Gluecron.com itself receives a push to
356 // main, fire the local deploy via scripts/self-deploy.sh. The script
357 // forks into the background, so this call returns immediately (git
358 // push doesn't block). Gated on env SELF_HOST_REPO (set on the box) to
359 // avoid firing on customer repos that happen to be named "Gluecron.com".
360 const selfHostRepo = process.env.SELF_HOST_REPO;
361 if (selfHostRepo && `${owner}/${repo}` === selfHostRepo) {
362 const mainRef = refs.find(
363 (r) => r.refName === "refs/heads/main" && !r.newSha.startsWith("0000")
364 );
365 if (mainRef) {
366 const scriptPath =
367 process.env.GLUECRON_SELF_DEPLOY_SCRIPT ||
368 "/opt/gluecron/scripts/self-deploy.sh";
369 try {
370 const child = __selfHostSpawn(
371 [scriptPath, mainRef.oldSha, mainRef.newSha],
372 { stdout: "ignore", stderr: "ignore", stdin: "ignore" }
373 );
374 try {
375 (child as any)?.unref?.();
376 } catch {
377 /* unref optional */
378 }
379 console.log(
380 `[self-host] dispatched self-deploy for ${owner}/${repo}@${mainRef.newSha.slice(0, 7)}`
381 );
382 } catch (err) {
383 console.error(`[self-host] failed to spawn:`, err);
384 }
385 }
386 }
387}
388
389// BLOCK W — DI seam so the test suite can capture the spawn call without
390// actually shelling out to /opt/gluecron/scripts/self-deploy.sh. Production
391// callers go straight to Bun.spawn.
bf19c50Test User392const __defaultSelfHostSpawn: (cmd: string[], opts: any) => any = (cmd, opts) =>
f2c00b4CC LABS App393 Bun.spawn(cmd, opts);
bf19c50Test User394let __selfHostSpawn: (cmd: string[], opts: any) => any = __defaultSelfHostSpawn;
395/**
396 * Test-only: replace the spawn impl. Pass `null` to reset to Bun.spawn.
397 */
398export function __setSelfHostSpawnForTests(
399 fn: typeof __selfHostSpawn | null
400): void {
401 __selfHostSpawn = fn ?? __defaultSelfHostSpawn;
fc1817aClaude402}
403
43cf9b0Claude404/**
9ecf5a4Claude405 * BLK-016 — outbound deploy webhook for Vapron's deploy-agent (formerly Crontech).
43cf9b0Claude406 *
9ecf5a4Claude407 * Wire contract (matches Vapron's `apps/api/src/webhooks/gluecron-push.ts`):
43cf9b0Claude408 *
9ecf5a4Claude409 * POST https://vapron.ai/api/webhooks/gluecron-push
43cf9b0Claude410 * Content-Type: application/json
ba93444Claude411 * X-Gluecron-Signature: sha256=<hex(hmac-sha256(body, GLUECRON_WEBHOOK_SECRET))>
43cf9b0Claude412 *
413 * {
ba93444Claude414 * "event": "push",
9ecf5a4Claude415 * "repository": { "full_name": "ccantynz-alt/vapron" },
ba93444Claude416 * "ref": "refs/heads/Main",
417 * "after": "<40-hex commit SHA>",
418 * "before": "<40-hex previous SHA>",
419 * "pusher": { "name": "<author>", "email": "<email>" },
420 * "commits": [ { "id": "<sha>", "message": "<msg>", "timestamp": "<iso8601>" } ]
43cf9b0Claude421 * }
422 *
ba93444Claude423 * The `after` SHA is the dedupe key on the receiver side (idempotent).
43cf9b0Claude424 *
ba93444Claude425 * Delivery: at-least-once via exponential-backoff retry. Up to 5 attempts at
426 * delays 1s / 4s / 16s / 64s / 256s; first 2xx wins. If `GLUECRON_WEBHOOK_SECRET`
9ecf5a4Claude427 * is unset the signature header is omitted and Vapron is expected to reject —
ba93444Claude428 * we still record the deploy row as failed.
43cf9b0Claude429 */
ba93444Claude430const RETRY_DELAYS_MS = [1_000, 4_000, 16_000, 64_000, 256_000];
431
432interface TriggerArgs {
433 owner: string;
434 repo: string;
435 before: string;
436 after: string;
437 ref: string;
438 branch: string;
439 repositoryId: string;
440}
441
442interface TriggerOptions {
443 fetchImpl?: typeof fetch;
444 sleep?: (ms: number) => Promise<void>;
445 retryDelaysMs?: number[];
446 now?: () => Date;
447}
448
449function signBody(body: string, secret: string): string | null {
450 if (!secret) return null;
451 return "sha256=" + createHmac("sha256", secret).update(body).digest("hex");
452}
453
454async function buildPayload(args: TriggerArgs, now: Date): Promise<{
455 payload: Record<string, unknown>;
456 pusherName: string;
457 pusherEmail: string;
458}> {
459 // Walk commits new since the last push. Cap at 50 like GitHub's webhook.
460 // `before` may be all-zeros for a first push to the branch — commitsBetween
461 // handles that by treating null `from` as "everything reachable from `to`".
462 const fromSha = /^0+$/.test(args.before) ? null : args.before;
463 let commits: Array<{ id: string; message: string; timestamp: string }> = [];
464 let pusherName = "gluecron";
465 let pusherEmail = "noreply@gluecron.local";
466 try {
467 const list = await commitsBetween(args.owner, args.repo, fromSha, args.after);
468 commits = list.slice(0, 50).map((c) => ({
469 id: c.sha,
470 message: c.message,
471 timestamp: c.date,
472 }));
473 if (list[0]) {
474 pusherName = list[0].author || pusherName;
475 pusherEmail = list[0].authorEmail || pusherEmail;
476 }
477 } catch {
478 /* ignore — payload still valid with empty commits[] */
479 }
480 return {
481 payload: {
482 event: "push",
483 repository: { full_name: `${args.owner}/${args.repo}` },
484 ref: args.ref,
485 after: args.after,
486 before: args.before,
487 pusher: { name: pusherName, email: pusherEmail },
488 commits,
489 // Ancillary fields — receiver may ignore but they're useful for logs:
490 sent_at: now.toISOString(),
491 source: "gluecron",
492 },
493 pusherName,
494 pusherEmail,
495 };
496}
497
9ecf5a4Claude498async function triggerVapronDeploy(
ba93444Claude499 args: TriggerArgs,
500 opts: TriggerOptions = {}
fc1817aClaude501): Promise<void> {
ba93444Claude502 const fetchImpl = opts.fetchImpl ?? fetch;
503 const sleep = opts.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
504 const delays = opts.retryDelaysMs ?? RETRY_DELAYS_MS;
505 const now = opts.now ?? (() => new Date());
506
3ef4c9dClaude507 let deployId = "";
fc1817aClaude508 try {
3ef4c9dClaude509 const [row] = await db
510 .insert(deployments)
511 .values({
ba93444Claude512 repositoryId: args.repositoryId,
3ef4c9dClaude513 environment: "production",
ba93444Claude514 commitSha: args.after,
515 ref: args.ref,
3ef4c9dClaude516 status: "pending",
9ecf5a4Claude517 target: "vapron",
3ef4c9dClaude518 })
519 .returning();
520 deployId = row?.id || "";
521 } catch {
522 /* ignore */
fc1817aClaude523 }
524
ba93444Claude525 const { payload } = await buildPayload(args, now());
526 const body = JSON.stringify(payload);
9ecf5a4Claude527 const signature = signBody(body, config.vapronHmacSecret);
ba93444Claude528
529 const headers: Record<string, string> = {
530 "Content-Type": "application/json",
531 "User-Agent": "gluecron-webhook/1",
532 "X-Gluecron-Event": "push",
533 "X-Gluecron-Delivery": cryptoRandomId(),
534 };
535 if (signature) headers["X-Gluecron-Signature"] = signature;
e61e6cdccanty labs536 // Vapron tenant auth: API key rides as a bearer alongside the HMAC
537 // signature (key = who is calling, signature = payload integrity).
538 if (config.vapronApiKey)
539 headers["Authorization"] = `Bearer ${config.vapronApiKey}`;
ba93444Claude540
541 let lastStatus = 0;
542 let lastError = "";
543 let success = false;
544
545 // Up to delays.length + 1 attempts (initial try + each delay).
546 const totalAttempts = delays.length + 1;
547 for (let attempt = 0; attempt < totalAttempts; attempt++) {
548 try {
9ecf5a4Claude549 const response = await fetchImpl(config.vapronDeployUrl, {
ba93444Claude550 method: "POST",
551 headers,
552 body,
553 });
554 lastStatus = response.status;
555 console.log(
9ecf5a4Claude556 `[vapron] attempt ${attempt + 1}/${totalAttempts} → ${lastStatus} for ${args.owner}/${args.repo}@${args.after.slice(0, 7)}`
ba93444Claude557 );
558 if (response.ok) {
559 success = true;
560 break;
561 }
562 // 4xx (except 408/429) is unrecoverable — stop retrying.
563 if (response.status >= 400 && response.status < 500 &&
564 response.status !== 408 && response.status !== 429) {
565 break;
566 }
567 } catch (err) {
568 lastError = err instanceof Error ? err.message : String(err);
569 console.error(
9ecf5a4Claude570 `[vapron] attempt ${attempt + 1}/${totalAttempts} failed: ${lastError}`
ba93444Claude571 );
3ef4c9dClaude572 }
ba93444Claude573 const nextDelay = delays[attempt];
574 if (nextDelay !== undefined && attempt < totalAttempts - 1) {
575 await sleep(nextDelay);
1e162a8Claude576 }
ba93444Claude577 }
578
579 if (deployId) {
580 try {
3ef4c9dClaude581 await db
582 .update(deployments)
583 .set({
ba93444Claude584 status: success ? "success" : "failed",
585 blockedReason: success
586 ? null
587 : (lastError ? lastError : `HTTP ${lastStatus}`),
3ef4c9dClaude588 completedAt: new Date(),
589 })
590 .where(eq(deployments.id, deployId));
ba93444Claude591 } catch {
592 /* ignore */
3ef4c9dClaude593 }
594 }
595
ba93444Claude596 if (!success && deployId) {
597 void onDeployFailure({
598 repositoryId: args.repositoryId,
599 deploymentId: deployId,
600 ref: args.ref,
601 commitSha: args.after,
9ecf5a4Claude602 target: "vapron",
ba93444Claude603 errorMessage: lastError || `HTTP ${lastStatus}`,
604 }).catch((e) => console.error("[ai-incident]", e));
fc1817aClaude605 }
606}
43cf9b0Claude607
ba93444Claude608function cryptoRandomId(): string {
609 // Short opaque delivery ID for log correlation. Not security-sensitive.
610 const bytes = new Uint8Array(8);
611 crypto.getRandomValues(bytes);
612 return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
613}
614
a686079Claude615/**
616 * Resolve `owner/repo` to its DB repository.id and dispatch the
617 * semantic-index update. Pulls the list of changed paths via
618 * `git diff --name-only`, dropping any deletions (handled implicitly
619 * because deleted blobs simply don't resolve in `indexChangedFiles`).
620 *
621 * Never throws — exhaust every external call inside a try/catch so the
622 * push completes even if Postgres or the embedding API is down.
623 */
624async function fireSemanticIndex(
625 owner: string,
626 repo: string,
627 oldSha: string,
628 newSha: string
629): Promise<void> {
630 let repositoryId = "";
631 try {
632 const [row] = await db
633 .select({ id: repositories.id })
634 .from(repositories)
635 .innerJoin(users, eq(repositories.ownerId, users.id))
636 .where(and(eq(users.username, owner), eq(repositories.name, repo)))
637 .limit(1);
638 repositoryId = row?.id || "";
639 } catch {
640 return;
641 }
642 if (!repositoryId) return;
643
644 let changedPaths: string[] = [];
645 try {
646 changedPaths = await listChangedPaths(owner, repo, oldSha, newSha);
647 } catch {
648 return;
649 }
650 if (!changedPaths.length) return;
651
652 try {
653 const out = await indexChangedFiles({
654 repositoryId,
655 ownerName: owner,
656 repoName: repo,
657 commitSha: newSha,
658 changedPaths,
659 });
660 if (out.indexed > 0) {
661 console.log(
662 `[semantic-index] ${owner}/${repo}@${newSha.slice(0, 7)}: indexed ${out.indexed} file(s) via ${out.model}`
663 );
664 }
665 } catch (err) {
666 console.warn("[semantic-index] indexChangedFiles error:", err);
667 }
668}
669
670/**
671 * Returns the list of files touched between `oldSha` and `newSha`. For
672 * the initial push on a branch (oldSha all-zero) we walk every file in
673 * the new tree via `git ls-tree -r`. Returns [] on any subprocess error.
674 */
675async function listChangedPaths(
676 owner: string,
677 repo: string,
678 oldSha: string,
679 newSha: string
680): Promise<string[]> {
681 const cwd = getRepoPath(owner, repo);
682 const allZero = /^0+$/.test(oldSha);
683 const cmd = allZero
684 ? ["git", "ls-tree", "-r", "--name-only", newSha]
685 : ["git", "diff", "--name-only", oldSha, newSha];
686 try {
687 const proc = Bun.spawn(cmd, {
688 cwd,
689 stdout: "pipe",
690 stderr: "pipe",
691 });
692 const text = await new Response(proc.stdout).text();
693 await proc.exited;
694 return text
695 .split("\n")
696 .map((s) => s.trim())
697 .filter((s) => s.length > 0);
698 } catch {
699 return [];
700 }
701}
702
4bbacbeClaude703/**
704 * Migration 0062 — fan out push refs to enqueuePreviewBuild for every
705 * non-default branch on a `preview_builds_enabled` repo.
706 *
707 * Resolves the repo row once, fetches the default branch + opt-out flag,
708 * then upserts one preview row per pushed ref that isn't the default.
709 * Branch deletions (oldSha all-zero or newSha all-zero with oldSha set)
710 * are skipped — they shouldn't create preview rows. Never throws.
711 */
712async function firePreviewBuilds(
713 owner: string,
714 repo: string,
715 refs: PushRef[]
716): Promise<void> {
717 // Filter to live branch pushes only.
718 const branchRefs = refs.filter(
719 (r) =>
720 r.refName.startsWith("refs/heads/") && !r.newSha.startsWith("0000")
721 );
722 if (branchRefs.length === 0) return;
723
724 let repoRow: { id: string; previewBuildsEnabled: boolean; defaultBranch: string } | null = null;
725 try {
726 const [row] = await db
727 .select({
728 id: repositories.id,
729 previewBuildsEnabled: repositories.previewBuildsEnabled,
730 defaultBranch: repositories.defaultBranch,
731 })
732 .from(repositories)
733 .innerJoin(users, eq(repositories.ownerId, users.id))
734 .where(and(eq(users.username, owner), eq(repositories.name, repo)))
735 .limit(1);
736 repoRow = row || null;
737 } catch {
738 return;
739 }
740 if (!repoRow) return;
741 if (!repoRow.previewBuildsEnabled) return;
742
743 for (const ref of branchRefs) {
744 const branchName = ref.refName.replace("refs/heads/", "");
745 if (branchName === repoRow.defaultBranch) continue;
746 try {
747 await enqueuePreviewBuild({
748 repositoryId: repoRow.id,
749 ownerName: owner,
750 repoName: repo,
751 branchName,
752 commitSha: ref.newSha,
753 });
754 } catch (err) {
755 console.warn(
756 `[branch-previews] enqueue failed for ${owner}/${repo}@${branchName}:`,
757 err instanceof Error ? err.message : err
758 );
759 }
760 }
761}
762
d199847Claude763/**
764 * Migration 0068 — resolve `owner/repo` to its DB id and kick off the
765 * doc-drift sweep (findTrackedDocs + proposeDocUpdate). Returns immediately
766 * on missing repo or DB error — pushes never block. Never throws.
767 */
768async function fireDocDriftCheck(owner: string, repo: string): Promise<void> {
769 let repositoryId = "";
770 try {
771 const [row] = await db
772 .select({ id: repositories.id })
773 .from(repositories)
774 .innerJoin(users, eq(repositories.ownerId, users.id))
775 .where(and(eq(users.username, owner), eq(repositories.name, repo)))
776 .limit(1);
777 repositoryId = row?.id || "";
778 } catch {
779 return;
780 }
781 if (!repositoryId) return;
782 try {
783 const out = await runDocDriftCheckForRepo(repositoryId);
784 if (out.docs > 0 || out.proposed > 0) {
785 console.log(
786 `[ai-doc-updater] ${owner}/${repo}: docs=${out.docs} proposed=${out.proposed}`
787 );
788 }
789 } catch (err) {
790 console.warn("[ai-doc-updater] runDocDriftCheckForRepo error:", err);
791 }
792}
793
783dd46Claude794/**
795 * Block ST — fan out the push to any server targets that watch this
796 * (repo, branch). One sequential deploy per target so a slow box can't
797 * stall the next push, but multiple matching targets run in parallel.
798 * Every failure is contained to its own deploy row + console warn —
799 * nothing here can break the push path.
800 */
801async function fireServerTargetDeploys(
802 owner: string,
803 repo: string,
804 refs: PushRef[]
805): Promise<void> {
806 const liveRefs = refs.filter(
807 (r) => r.refName.startsWith("refs/heads/") && !r.newSha.startsWith("0000")
808 );
809 if (liveRefs.length === 0) return;
810
811 let repositoryId = "";
812 try {
813 const [row] = await db
814 .select({ id: repositories.id })
815 .from(repositories)
816 .innerJoin(users, eq(repositories.ownerId, users.id))
817 .where(and(eq(users.username, owner), eq(repositories.name, repo)))
818 .limit(1);
819 repositoryId = row?.id || "";
820 } catch {
821 return;
822 }
823 if (!repositoryId) return;
824
825 await Promise.all(
826 liveRefs.map(async (ref) => {
827 const branch = ref.refName.replace("refs/heads/", "");
828 let targets;
829 try {
830 targets = await findTargetsForPush({ repositoryId, branch });
831 } catch {
832 return;
833 }
834 if (!targets.length) return;
835
836 await Promise.all(
837 targets.map(async (target) => {
838 try {
839 const env = await resolveEnv(target.id);
840 const deployId = await startDeployRow({
841 targetId: target.id,
842 commitSha: ref.newSha,
843 ref: ref.refName,
844 triggerSource: "push",
845 });
846 const result = await deployToTarget(target, {
847 commitSha: ref.newSha,
848 ref: ref.refName,
849 env,
850 });
851 if (deployId) {
852 await finishDeployRow({
853 id: deployId,
854 exitCode: result.exitCode,
855 stdout: result.stdout,
856 stderr: result.stderr,
857 });
858 }
859 console.log(
860 `[server-targets] ${target.name} @ ${ref.newSha.slice(0, 7)}: exit ${result.exitCode}`
861 );
862 } catch (err) {
863 console.warn(
864 `[server-targets] ${target.name}: deploy threw — ${err instanceof Error ? err.message : err}`
865 );
866 }
867 })
868 );
869 })
870 );
871}
872
da3fc18Claude873/**
874 * Fire-and-forget wrapper around scanDependencies for each pushed ref.
875 * Resolves the repo DB row once, then runs the scanner on each live push.
876 * Swallows all errors so a scanner failure never affects the push path.
877 */
878async function fireDependencyScan(
879 owner: string,
880 repo: string,
881 refs: PushRef[]
882): Promise<void> {
883 const liveRefs = refs.filter(
884 (r) => r.refName.startsWith("refs/heads/") && !r.newSha.startsWith("0000")
885 );
886 if (liveRefs.length === 0) return;
887
888 let repoRow: { id: string; ownerId: string } | null = null;
889 try {
890 const [row] = await db
891 .select({ id: repositories.id, ownerId: repositories.ownerId })
892 .from(repositories)
893 .innerJoin(users, eq(repositories.ownerId, users.id))
894 .where(and(eq(users.username, owner), eq(repositories.name, repo)))
895 .limit(1);
896 repoRow = row || null;
897 } catch {
898 return;
899 }
900 if (!repoRow) return;
901
902 for (const ref of liveRefs) {
903 try {
904 const findings = await scanDependencies(
905 repoRow.id,
906 owner,
907 repo,
908 ref.newSha,
909 ref.oldSha,
910 repoRow.ownerId
911 );
912 if (findings.length > 0) {
913 console.log(
914 `[dependency-scanner] ${owner}/${repo}@${ref.newSha.slice(0, 7)}: ${findings.length} finding(s)`
915 );
916 }
917 } catch (err) {
918 console.warn(
919 `[dependency-scanner] scan threw for ${owner}/${repo}@${ref.newSha.slice(0, 7)}:`,
920 err instanceof Error ? err.message : err
921 );
922 }
923 }
924}
925
9c5223fClaude926/**
927 * Migration 0088 — trigger repo onboarding on first push to the default branch.
928 * Detects "first push" by checking whether oldSha is all-zeros on a push to
929 * the repo's default branch (or any branch for a repo with no prior history).
930 * Resolves the repo DB id, then calls ensureRepoOnboarding which is idempotent.
931 * Never throws.
932 */
933async function fireRepoOnboarding(
934 owner: string,
935 repo: string,
936 refs: PushRef[]
937): Promise<void> {
938 // Only fire on first push — oldSha all-zeros means the branch is brand-new.
939 const firstPushRefs = refs.filter(
940 (r) => r.refName.startsWith("refs/heads/") && /^0+$/.test(r.oldSha) && !r.newSha.startsWith("0000")
941 );
942 if (firstPushRefs.length === 0) return;
943
944 let repositoryId = "";
945 try {
946 const [row] = await db
947 .select({ id: repositories.id })
948 .from(repositories)
949 .innerJoin(users, eq(repositories.ownerId, users.id))
950 .where(and(eq(users.username, owner), eq(repositories.name, repo)))
951 .limit(1);
952 repositoryId = row?.id || "";
953 } catch {
954 return;
955 }
956 if (!repositoryId) return;
957
958 await ensureRepoOnboarding(repositoryId, owner, repo);
959}
960
43cf9b0Claude961/** Test-only access to internal helpers. */
a686079Claude962export const __test = {
9ecf5a4Claude963 triggerVapronDeploy,
a686079Claude964 signBody,
965 buildPayload,
966 RETRY_DELAYS_MS,
967 listChangedPaths,
968 fireSemanticIndex,
4bbacbeClaude969 firePreviewBuilds,
d199847Claude970 fireDocDriftCheck,
783dd46Claude971 fireServerTargetDeploys,
da3fc18Claude972 fireDependencyScan,
9c5223fClaude973 fireRepoOnboarding,
a686079Claude974};