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.tsBlame970 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
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;
536
537 let lastStatus = 0;
538 let lastError = "";
539 let success = false;
540
541 // Up to delays.length + 1 attempts (initial try + each delay).
542 const totalAttempts = delays.length + 1;
543 for (let attempt = 0; attempt < totalAttempts; attempt++) {
544 try {
9ecf5a4Claude545 const response = await fetchImpl(config.vapronDeployUrl, {
ba93444Claude546 method: "POST",
547 headers,
548 body,
549 });
550 lastStatus = response.status;
551 console.log(
9ecf5a4Claude552 `[vapron] attempt ${attempt + 1}/${totalAttempts} → ${lastStatus} for ${args.owner}/${args.repo}@${args.after.slice(0, 7)}`
ba93444Claude553 );
554 if (response.ok) {
555 success = true;
556 break;
557 }
558 // 4xx (except 408/429) is unrecoverable — stop retrying.
559 if (response.status >= 400 && response.status < 500 &&
560 response.status !== 408 && response.status !== 429) {
561 break;
562 }
563 } catch (err) {
564 lastError = err instanceof Error ? err.message : String(err);
565 console.error(
9ecf5a4Claude566 `[vapron] attempt ${attempt + 1}/${totalAttempts} failed: ${lastError}`
ba93444Claude567 );
3ef4c9dClaude568 }
ba93444Claude569 const nextDelay = delays[attempt];
570 if (nextDelay !== undefined && attempt < totalAttempts - 1) {
571 await sleep(nextDelay);
1e162a8Claude572 }
ba93444Claude573 }
574
575 if (deployId) {
576 try {
3ef4c9dClaude577 await db
578 .update(deployments)
579 .set({
ba93444Claude580 status: success ? "success" : "failed",
581 blockedReason: success
582 ? null
583 : (lastError ? lastError : `HTTP ${lastStatus}`),
3ef4c9dClaude584 completedAt: new Date(),
585 })
586 .where(eq(deployments.id, deployId));
ba93444Claude587 } catch {
588 /* ignore */
3ef4c9dClaude589 }
590 }
591
ba93444Claude592 if (!success && deployId) {
593 void onDeployFailure({
594 repositoryId: args.repositoryId,
595 deploymentId: deployId,
596 ref: args.ref,
597 commitSha: args.after,
9ecf5a4Claude598 target: "vapron",
ba93444Claude599 errorMessage: lastError || `HTTP ${lastStatus}`,
600 }).catch((e) => console.error("[ai-incident]", e));
fc1817aClaude601 }
602}
43cf9b0Claude603
ba93444Claude604function cryptoRandomId(): string {
605 // Short opaque delivery ID for log correlation. Not security-sensitive.
606 const bytes = new Uint8Array(8);
607 crypto.getRandomValues(bytes);
608 return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
609}
610
a686079Claude611/**
612 * Resolve `owner/repo` to its DB repository.id and dispatch the
613 * semantic-index update. Pulls the list of changed paths via
614 * `git diff --name-only`, dropping any deletions (handled implicitly
615 * because deleted blobs simply don't resolve in `indexChangedFiles`).
616 *
617 * Never throws — exhaust every external call inside a try/catch so the
618 * push completes even if Postgres or the embedding API is down.
619 */
620async function fireSemanticIndex(
621 owner: string,
622 repo: string,
623 oldSha: string,
624 newSha: string
625): Promise<void> {
626 let repositoryId = "";
627 try {
628 const [row] = await db
629 .select({ id: repositories.id })
630 .from(repositories)
631 .innerJoin(users, eq(repositories.ownerId, users.id))
632 .where(and(eq(users.username, owner), eq(repositories.name, repo)))
633 .limit(1);
634 repositoryId = row?.id || "";
635 } catch {
636 return;
637 }
638 if (!repositoryId) return;
639
640 let changedPaths: string[] = [];
641 try {
642 changedPaths = await listChangedPaths(owner, repo, oldSha, newSha);
643 } catch {
644 return;
645 }
646 if (!changedPaths.length) return;
647
648 try {
649 const out = await indexChangedFiles({
650 repositoryId,
651 ownerName: owner,
652 repoName: repo,
653 commitSha: newSha,
654 changedPaths,
655 });
656 if (out.indexed > 0) {
657 console.log(
658 `[semantic-index] ${owner}/${repo}@${newSha.slice(0, 7)}: indexed ${out.indexed} file(s) via ${out.model}`
659 );
660 }
661 } catch (err) {
662 console.warn("[semantic-index] indexChangedFiles error:", err);
663 }
664}
665
666/**
667 * Returns the list of files touched between `oldSha` and `newSha`. For
668 * the initial push on a branch (oldSha all-zero) we walk every file in
669 * the new tree via `git ls-tree -r`. Returns [] on any subprocess error.
670 */
671async function listChangedPaths(
672 owner: string,
673 repo: string,
674 oldSha: string,
675 newSha: string
676): Promise<string[]> {
677 const cwd = getRepoPath(owner, repo);
678 const allZero = /^0+$/.test(oldSha);
679 const cmd = allZero
680 ? ["git", "ls-tree", "-r", "--name-only", newSha]
681 : ["git", "diff", "--name-only", oldSha, newSha];
682 try {
683 const proc = Bun.spawn(cmd, {
684 cwd,
685 stdout: "pipe",
686 stderr: "pipe",
687 });
688 const text = await new Response(proc.stdout).text();
689 await proc.exited;
690 return text
691 .split("\n")
692 .map((s) => s.trim())
693 .filter((s) => s.length > 0);
694 } catch {
695 return [];
696 }
697}
698
4bbacbeClaude699/**
700 * Migration 0062 — fan out push refs to enqueuePreviewBuild for every
701 * non-default branch on a `preview_builds_enabled` repo.
702 *
703 * Resolves the repo row once, fetches the default branch + opt-out flag,
704 * then upserts one preview row per pushed ref that isn't the default.
705 * Branch deletions (oldSha all-zero or newSha all-zero with oldSha set)
706 * are skipped — they shouldn't create preview rows. Never throws.
707 */
708async function firePreviewBuilds(
709 owner: string,
710 repo: string,
711 refs: PushRef[]
712): Promise<void> {
713 // Filter to live branch pushes only.
714 const branchRefs = refs.filter(
715 (r) =>
716 r.refName.startsWith("refs/heads/") && !r.newSha.startsWith("0000")
717 );
718 if (branchRefs.length === 0) return;
719
720 let repoRow: { id: string; previewBuildsEnabled: boolean; defaultBranch: string } | null = null;
721 try {
722 const [row] = await db
723 .select({
724 id: repositories.id,
725 previewBuildsEnabled: repositories.previewBuildsEnabled,
726 defaultBranch: repositories.defaultBranch,
727 })
728 .from(repositories)
729 .innerJoin(users, eq(repositories.ownerId, users.id))
730 .where(and(eq(users.username, owner), eq(repositories.name, repo)))
731 .limit(1);
732 repoRow = row || null;
733 } catch {
734 return;
735 }
736 if (!repoRow) return;
737 if (!repoRow.previewBuildsEnabled) return;
738
739 for (const ref of branchRefs) {
740 const branchName = ref.refName.replace("refs/heads/", "");
741 if (branchName === repoRow.defaultBranch) continue;
742 try {
743 await enqueuePreviewBuild({
744 repositoryId: repoRow.id,
745 ownerName: owner,
746 repoName: repo,
747 branchName,
748 commitSha: ref.newSha,
749 });
750 } catch (err) {
751 console.warn(
752 `[branch-previews] enqueue failed for ${owner}/${repo}@${branchName}:`,
753 err instanceof Error ? err.message : err
754 );
755 }
756 }
757}
758
d199847Claude759/**
760 * Migration 0068 — resolve `owner/repo` to its DB id and kick off the
761 * doc-drift sweep (findTrackedDocs + proposeDocUpdate). Returns immediately
762 * on missing repo or DB error — pushes never block. Never throws.
763 */
764async function fireDocDriftCheck(owner: string, repo: string): Promise<void> {
765 let repositoryId = "";
766 try {
767 const [row] = await db
768 .select({ id: repositories.id })
769 .from(repositories)
770 .innerJoin(users, eq(repositories.ownerId, users.id))
771 .where(and(eq(users.username, owner), eq(repositories.name, repo)))
772 .limit(1);
773 repositoryId = row?.id || "";
774 } catch {
775 return;
776 }
777 if (!repositoryId) return;
778 try {
779 const out = await runDocDriftCheckForRepo(repositoryId);
780 if (out.docs > 0 || out.proposed > 0) {
781 console.log(
782 `[ai-doc-updater] ${owner}/${repo}: docs=${out.docs} proposed=${out.proposed}`
783 );
784 }
785 } catch (err) {
786 console.warn("[ai-doc-updater] runDocDriftCheckForRepo error:", err);
787 }
788}
789
783dd46Claude790/**
791 * Block ST — fan out the push to any server targets that watch this
792 * (repo, branch). One sequential deploy per target so a slow box can't
793 * stall the next push, but multiple matching targets run in parallel.
794 * Every failure is contained to its own deploy row + console warn —
795 * nothing here can break the push path.
796 */
797async function fireServerTargetDeploys(
798 owner: string,
799 repo: string,
800 refs: PushRef[]
801): Promise<void> {
802 const liveRefs = refs.filter(
803 (r) => r.refName.startsWith("refs/heads/") && !r.newSha.startsWith("0000")
804 );
805 if (liveRefs.length === 0) return;
806
807 let repositoryId = "";
808 try {
809 const [row] = await db
810 .select({ id: repositories.id })
811 .from(repositories)
812 .innerJoin(users, eq(repositories.ownerId, users.id))
813 .where(and(eq(users.username, owner), eq(repositories.name, repo)))
814 .limit(1);
815 repositoryId = row?.id || "";
816 } catch {
817 return;
818 }
819 if (!repositoryId) return;
820
821 await Promise.all(
822 liveRefs.map(async (ref) => {
823 const branch = ref.refName.replace("refs/heads/", "");
824 let targets;
825 try {
826 targets = await findTargetsForPush({ repositoryId, branch });
827 } catch {
828 return;
829 }
830 if (!targets.length) return;
831
832 await Promise.all(
833 targets.map(async (target) => {
834 try {
835 const env = await resolveEnv(target.id);
836 const deployId = await startDeployRow({
837 targetId: target.id,
838 commitSha: ref.newSha,
839 ref: ref.refName,
840 triggerSource: "push",
841 });
842 const result = await deployToTarget(target, {
843 commitSha: ref.newSha,
844 ref: ref.refName,
845 env,
846 });
847 if (deployId) {
848 await finishDeployRow({
849 id: deployId,
850 exitCode: result.exitCode,
851 stdout: result.stdout,
852 stderr: result.stderr,
853 });
854 }
855 console.log(
856 `[server-targets] ${target.name} @ ${ref.newSha.slice(0, 7)}: exit ${result.exitCode}`
857 );
858 } catch (err) {
859 console.warn(
860 `[server-targets] ${target.name}: deploy threw — ${err instanceof Error ? err.message : err}`
861 );
862 }
863 })
864 );
865 })
866 );
867}
868
da3fc18Claude869/**
870 * Fire-and-forget wrapper around scanDependencies for each pushed ref.
871 * Resolves the repo DB row once, then runs the scanner on each live push.
872 * Swallows all errors so a scanner failure never affects the push path.
873 */
874async function fireDependencyScan(
875 owner: string,
876 repo: string,
877 refs: PushRef[]
878): Promise<void> {
879 const liveRefs = refs.filter(
880 (r) => r.refName.startsWith("refs/heads/") && !r.newSha.startsWith("0000")
881 );
882 if (liveRefs.length === 0) return;
883
884 let repoRow: { id: string; ownerId: string } | null = null;
885 try {
886 const [row] = await db
887 .select({ id: repositories.id, ownerId: repositories.ownerId })
888 .from(repositories)
889 .innerJoin(users, eq(repositories.ownerId, users.id))
890 .where(and(eq(users.username, owner), eq(repositories.name, repo)))
891 .limit(1);
892 repoRow = row || null;
893 } catch {
894 return;
895 }
896 if (!repoRow) return;
897
898 for (const ref of liveRefs) {
899 try {
900 const findings = await scanDependencies(
901 repoRow.id,
902 owner,
903 repo,
904 ref.newSha,
905 ref.oldSha,
906 repoRow.ownerId
907 );
908 if (findings.length > 0) {
909 console.log(
910 `[dependency-scanner] ${owner}/${repo}@${ref.newSha.slice(0, 7)}: ${findings.length} finding(s)`
911 );
912 }
913 } catch (err) {
914 console.warn(
915 `[dependency-scanner] scan threw for ${owner}/${repo}@${ref.newSha.slice(0, 7)}:`,
916 err instanceof Error ? err.message : err
917 );
918 }
919 }
920}
921
9c5223fClaude922/**
923 * Migration 0088 — trigger repo onboarding on first push to the default branch.
924 * Detects "first push" by checking whether oldSha is all-zeros on a push to
925 * the repo's default branch (or any branch for a repo with no prior history).
926 * Resolves the repo DB id, then calls ensureRepoOnboarding which is idempotent.
927 * Never throws.
928 */
929async function fireRepoOnboarding(
930 owner: string,
931 repo: string,
932 refs: PushRef[]
933): Promise<void> {
934 // Only fire on first push — oldSha all-zeros means the branch is brand-new.
935 const firstPushRefs = refs.filter(
936 (r) => r.refName.startsWith("refs/heads/") && /^0+$/.test(r.oldSha) && !r.newSha.startsWith("0000")
937 );
938 if (firstPushRefs.length === 0) return;
939
940 let repositoryId = "";
941 try {
942 const [row] = await db
943 .select({ id: repositories.id })
944 .from(repositories)
945 .innerJoin(users, eq(repositories.ownerId, users.id))
946 .where(and(eq(users.username, owner), eq(repositories.name, repo)))
947 .limit(1);
948 repositoryId = row?.id || "";
949 } catch {
950 return;
951 }
952 if (!repositoryId) return;
953
954 await ensureRepoOnboarding(repositoryId, owner, repo);
955}
956
43cf9b0Claude957/** Test-only access to internal helpers. */
a686079Claude958export const __test = {
9ecf5a4Claude959 triggerVapronDeploy,
a686079Claude960 signBody,
961 buildPayload,
962 RETRY_DELAYS_MS,
963 listChangedPaths,
964 fireSemanticIndex,
4bbacbeClaude965 firePreviewBuilds,
d199847Claude966 fireDocDriftCheck,
783dd46Claude967 fireServerTargetDeploys,
da3fc18Claude968 fireDependencyScan,
9c5223fClaude969 fireRepoOnboarding,
a686079Claude970};